-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay 076 - Wiggle Subsequence
57 lines (48 loc) · 1.68 KB
/
Day 076 - Wiggle Subsequence
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
51
52
53
54
55
56
57
// ( --- https://leetcode.com/problems/wiggle-subsequence/ --- )
public class Solution { // t.c :- O(n)
public int wiggleMaxLength(int[] nums) {
if (nums.length == 0) return 0;
int up = 1, down = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] < nums[i - 1]) down = up + 1;
else if (nums[i] > nums[i - 1]) up = down + 1;
}
return Math.max(up, down);
}
}
hint :- https://www.youtube.com/watch?v=xtDu3jm5WsI&ab_channel=alGOds
// others code
public int wiggle(int[] a) { //t.c = O(n)
if(a.length < 2) return a.length;
int i = 1; while(i < a.length && a[i] == a[i-1]) i++;
if(i == a.length) return 1;
int c = 2;
boolean inc = a[i] > a[i-1];
while(i < a.length) {
if(inc) {
while(i < a.length && a[i] >= a[i-1]) i++;
if(i < a.length) c++; inc = false;
}
else {
while(i < a.length && a[i] <= a[i-1]) i++;
if(i < a.length) c++; inc = true;
}
}
return c;
}
// DP like LIS
public int wiggleDPSolution(int[] a) { // t.c:- O(n*n)
if(a.length < 2) return a.length;
int inc[] = new int[a.length], dec[] = new int[a.length];
Arrays.fill(inc,1);
Arrays.fill(dec,1);
int ans = 1;
for(int i=1;i<a.length;i++) {
for(int j=0;j<i;j++) {
if(a[j] < a[i]) inc[i] = Math.max(inc[i],1+dec[j]);
if(a[j] > a[i]) dec[i] = Math.max(dec[i],1+inc[j]);
}
ans = Math.max(ans,Math.max(inc[i],dec[i]));
}
return ans;
}