프로그래머스 코딩테스트 연습문제 (혼자 놀기의 달인)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Stack;
import java.lang.Boolean;
class Dfs{
ArrayList<Integer> max = new ArrayList<>();
Stack<Integer> sta = new Stack<>();
int[] card = {};
boolean[] check = {};
void setCard(int[] cards, int len){
card = new int[len];
card = cards;
check = new boolean[len];
Arrays.fill(check,false);
}
void loop(int i){
if(check[i]) {
max.add(sta.size());
return;
}
else{
check[i]=true;
sta.add(1);
i=card[i]-1;
loop(i);
sta.pop();
}
if(sta.empty()){
for(int k=0; k<card.length; k++){
if(!check[k]) loop(k);
}
}
}
int getResult(){
int[] a = max.stream().mapToInt(i->i).toArray();
Arrays.sort(a);
if(a.length==1) return 0;
return a[a.length-1]*a[a.length-2];
}
}
class Solution {
public int solution(int[] cards) {
int answer = 0;
Dfs df = new Dfs();
df.setCard(cards, cards.length);
df.loop(0);
answer = df.getResult();
return answer;
}
}
댓글