프로그래머스/2레벨
[프로그래머스/C++] 혼자 놀기의 달인
Koalitsiya
2024. 3. 10. 21:06
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int solution(vector<int> cards) {
int answer = 0;
int n = cards.size();
// 해당 숫자의 카드가 선택되었는지 체크
bool selected[101] = {false};
vector<int> results;
for(int i =0; i < n; i++) {
int cur = cards[i], cnt = 0;
// 이미 선택된 카드가 나오지 않을때까지 카드 뽑기
while(!selected[cur]) {
selected[cur] = true;
cur = cards[cur - 1];
cnt++;
}
if(cnt > 0) results.push_back(cnt);
}
if(results.size() > 1) {
// 배열을 내림차순으로 정렬
sort(results.begin(), results.end(), greater<int>());
// 가장 큰 값 2개를 곱한 뒤 리턴
return results[0] * results[1];
}
return 0;
}