-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestWiggleSequence.java
More file actions
43 lines (31 loc) · 1.14 KB
/
LongestWiggleSequence.java
File metadata and controls
43 lines (31 loc) · 1.14 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
// DP O(n^2) solution, took about an hour. O(n) solution exist with up & down array
import java.util.*;
class Solution {
public int wiggleMaxLength(int[] nums) {
if(nums.length < 2){
return nums.length;
}
int[] vals = new int[nums.length];
Arrays.fill(vals,1);
boolean[] bools = new boolean[nums.length];
int max = 1;
for(int j = 1; j < nums.length; j++){
for(int i = 0; i < j; i++){
if(nums[i] == nums[j]){
continue;
}
boolean currb = nums[j] >= nums[i];
if(i == 0 || currb != bools[i]){
if(vals[i] + 1 >= vals[j]){
bools[j] = currb;
}
vals[j] = Math.max(vals[i] + 1, vals[j]);
if(max < vals[j]){
max = vals[j];
}
}
}
}
return max;
}
}