-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgrammers_131130.java
More file actions
44 lines (38 loc) · 1.18 KB
/
Copy pathProgrammers_131130.java
File metadata and controls
44 lines (38 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package programmers.lv2;
import java.util.ArrayList;
import java.util.Comparator;
public class Programmers_131130 {
public static void main(String[] args) {
Programmers_131130 test = new Programmers_131130();
int[] cards = { 8, 6, 3, 7, 2, 5, 1, 4 };
int result = test.solution(cards);
System.out.println("result: " + result);
}
boolean[] visited;
public int solution(int[] cards) {
visited = new boolean[cards.length];
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < cards.length; i++) {
int idx = cards[i] - 1;
if (!visited[idx]) {
int size = dfs(idx, cards);
list.add(size);
}
}
list.sort(Comparator.reverseOrder());
System.out.println(list.toString());
int answer = 0;
if (list.size() > 1) {
answer = list.get(0) * list.get(1);
}
return answer;
}
public int dfs(int idx, int[] cards) {
visited[idx] = true;
int newIdx = cards[idx] - 1;
if (!visited[newIdx]) {
return 1 + dfs(newIdx, cards);
}
return 1;
}
}