알고리즘
프로그래머스 혼자 놀기의 달인 (JAVA)
박카스마시며코딩
2023. 5. 1. 21:49
https://school.programmers.co.kr/learn/courses/30/lessons/131130
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
import java.util.*;
class Solution {
public int solution(int[] cards) {
int answer = 0;
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
int size = cards.length;
boolean[] used = new boolean[size];
for(int i = 0 ; i < size ; i++){
if(!used[i]){
int cnt = cal(i,used,cards);
pq.offer(cnt);
}
}
if(pq.size() < 2){
return 0;
}
answer = pq.poll();
answer *= pq.poll();
return answer;
}
private static int cal(int index, boolean[] used, int[] cards){
int cnt = 0;
while(!used[index]){
used[index] = true;
index = cards[index]-1;
cnt++;
}
return cnt;
}
}