-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathArrayNesting_565.java
More file actions
40 lines (40 loc) · 1.15 KB
/
ArrayNesting_565.java
File metadata and controls
40 lines (40 loc) · 1.15 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
public class ArrayNesting_565 {
public static int arrayNesting(int[] nums) {
/* Most voted solution
int maxsize = 0;
for (int i = 0; i < nums.length; i++) {
int size = 0;
for (int k = i; nums[k] >= 0; size++) {
int ak = nums[k];
nums[k] = -1; // mark a[k] as visited;
k = ak;
}
maxsize = Integer.max(maxsize, size);
}
return maxsize;
*/
int res = 0;
int count = 0;
boolean[] seen = new boolean[nums.length];
for (int i=0; i<nums.length; i++) {
if (seen[i])
continue;
int j = i;
int max = 0;
do {
max++;
seen[j] = true;
j = nums[j];
} while (j != i);
res = Math.max(res, max);
count += max;
if (nums.length - count <= res)
return res;
}
return res;
}
public static void main (String args[]) {
int[] testNums = {5,4,0,3,1,6,2};
System.out.println(arrayNesting(testNums));
}
}