-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
50 lines (45 loc) · 1.19 KB
/
Copy pathSolution.java
File metadata and controls
50 lines (45 loc) · 1.19 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
45
46
47
48
49
50
import java.util.Arrays;
public class Solution
{
private Integer maxLen;
public int arrayNesting(int[] nums)
{
maxLen = Integer.MIN_VALUE;
int[] dp = new int[nums.length];
Arrays.fill(dp, Integer.MAX_VALUE);
for (int i = 0; i < nums.length; i++)
{
if (dp[i] == Integer.MAX_VALUE)
{
if (populateCyclicLens(nums, i, dp))
{
break;
}
}
}
return maxLen;
}
private boolean populateCyclicLens(int[] nums, int i, int[] dp)
{
int idx = i;
int count = 0;
boolean[] visited = new boolean[nums.length];
while (!visited[idx])
{
visited[idx] = true;
idx = nums[idx];
count++;
}
boolean filled = true;
for (int j = 0; j < nums.length; j++)
{
if (visited[j])
{
dp[j] = Math.min(count, dp[j]);
}
filled = dp[j] == Integer.MAX_VALUE ? false : filled;
maxLen = dp[j] == Integer.MAX_VALUE ? maxLen : Math.max(maxLen, dp[j]);
}
return filled;
}
}