스타 수열

108번뇌·2021년 10월 26일

https://programmers.co.kr/learn/courses/30/lessons/70130

이 문제 이해하는데도 오래걸렸고,
결국 못풀어서 답보고 이해했는데도 오래걸렸음.

#include <string>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;

int solution(vector<int> a)
{
	int answer = -1;

	map<int, int> m_con;
	for (int i = 0; i < a.size(); i++)
	{
		m_con[a[i]]++;
	}

	map<int, int>::iterator m_itr;

	for (m_itr = m_con.begin(); m_itr != m_con.end(); m_itr++)
	{
		int RST(0);
		if (m_itr->second < answer) continue;

		for (int j = 0; j < a.size()-1; j++)
		{
			

			if (m_itr->first != a[j] && m_itr->first != a[j+1])
			{
				continue;
			}
			if (a[j] == a[j + 1])
			{
				continue;
			}
				j++;
				RST++;
		}
		answer = max(answer, RST);
	}

	return answer * 2;
}

int main()
{
	vector<int> vTemp = { 5,2,3,3,5,3 };

	int vResult = solution(vTemp);

	return 0;
}
  1. 먼저맵으로 각 해당 원소가 몇개씩 있는지 파악

  2. 첫째 if 를 안해주면 타임아웃 난다.
    기본적으로 max(answer) 보다 작은 스타수열의 절반 길이 이면 for문 검사 할 필요도 없다.

  3. ㄱ. 이중포문안의 첫번째 if는 연속되는 a[j], a[j+1]배열에서 둘중 하나라도 map의 원소를 가져야 진행된다
    ㄴ. 스타수열의 규칙인데 공통원소를 하나라도 가지면서(2개중 1개) && 그 가지는 원소가 연속적이면 안되는 조건
    ㄱ과 ㄴ을 만족하면 RST++를 해주고

  4. 최종적으로 return 할때 스타스열의 공통원소는 빼고 계산했으므로 return answer*2를 해준다.

profile
내일 아침 눈을 떳을 때, '기대되는 오늘 하루를 만들기 위해' 나는 오늘도 생각하고 고민한다.

0개의 댓글