-
Notifications
You must be signed in to change notification settings - Fork 0
/
DP-978. Longest Turbulent Subarray.cpp
77 lines (69 loc) · 1.73 KB
/
DP-978. Longest Turbulent Subarray.cpp
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// 978. Longest Turbulent Subarray
class Solution {
public:
// There are 2 possibilities either we check v[0]>v[1] or we check v[0]<v[1]
// so, we will check for both case
// Whoever returns maximum that will be our answer
int maxTurbulenceSize(vector<int>& v) {
int n=v.size();
vector<int> dp(n+1,1);
bool less=true; //first check for dp[0]<dp[1]
for(int i=1;i<n;i++)
{
if(less)
{
if(v[i-1]<v[i])
{
dp[i]=dp[i-1]+1;
}
less=false;
}
else{
if(v[i-1]>v[i])
{
dp[i]=dp[i-1]+1;
}
less=true;
}
}
for(auto it:dp){
cout<<it<<" ";
}
cout<<"\n";
// find out the best answer from this
int ans=0;
for(int i=0;i<n;i++)
{
ans=max(ans,dp[i]);
dp[i]=1;
}
bool greater=true; //now check for dp[0]>dp[1]
for(int i=1;i<n;i++)
{
if(greater)
{
if(v[i-1]>v[i])
{
dp[i]=dp[i-1]+1;
}
greater=false;
}
else{
if(v[i-1]<v[i])
{
dp[i]=dp[i-1]+1;
}
greater=true;
}
}
for(auto it:dp){
cout<<it<<" ";
}
cout<<"\n";
for(int i=0;i<n;i++)
{
ans=max(ans,dp[i]);
}
return ans;
}
};