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;
}
}
'알고리즘' 카테고리의 다른 글
프로그래머스 코드 처리하기 (JAVA) (0) | 2023.05.03 |
---|---|
프로그래머스 그림 확대 (JAVA) (0) | 2023.05.02 |
프로그래머스 광물 캐기 (JAVA) (0) | 2023.04.30 |
프로그래머스 디펜스 게임 (JAVA) (0) | 2023.04.29 |
프로그래머스 2의 영역(JAVA) (0) | 2023.04.28 |