-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.java
More file actions
148 lines (145 loc) · 4.27 KB
/
Copy pathsolution.java
File metadata and controls
148 lines (145 loc) · 4.27 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
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
// 978. Longest Turbulent Subarray
// https://leetcode.com/problems/longest-turbulent-subarray/
// Medium | Java | Accepted 2026-08-24
// Runtime 6 ms | Memory 51.8 MB
/*
class Solution {
public int maxTurbulenceSize(int[] arr) {
//My solution is optimal (beats 98%) but complicated
//My intuition is to go through the array and find various points that fit the turbulent criteria
//Move the left and right pointers out as far as possible to find the longest turbulent subarray
//Default answer is 2 if there are more than 1 element and the array doesn't have all the same elements
if(arr.length==1)
{
return 1;
}
int ans = 2;
int ind = 1;
int countSame = 0;
int ind2 = 0;
for(int i = 1; i<arr.length; i++)
{
if(arr[i-1]==arr[i])
{
countSame++;
}
}
if(countSame==arr.length-1)
{
return 1;
}
while(ind<arr.length-1)
{
if(arr[ind-1]>arr[ind] && arr[ind+1]>arr[ind])
{
int left = ind-1;
int right = ind+1;
boolean flag = false;
while(left-1>=0)
{
if(!flag && arr[left-1]<arr[left])
{
left--;
flag = !flag;
continue;
}
else if(flag && arr[left-1]>arr[left])
{
left--;
flag = !flag;
continue;
}
break;
}
flag = false;
while(right+1<arr.length)
{
if(!flag && arr[right+1]<arr[right])
{
right++;
flag = !flag;
continue;
}
else if(flag && arr[right+1]>arr[right])
{
right++;
flag = !flag;
continue;
}
break;
}
ans = Math.max(ans, right-left+1);
ind = right;
}
else if(arr[ind-1]<arr[ind] && arr[ind+1]<arr[ind])
{
int left = ind-1;
int right = ind+1;
boolean flag = false;
while(left-1>=0)
{
if(!flag && arr[left-1]>arr[left])
{
left--;
flag = !flag;
continue;
}
else if(flag && arr[left-1]<arr[left])
{
left--;
flag = !flag;
continue;
}
break;
}
flag = false;
while(right+1<arr.length)
{
if(!flag && arr[right+1]>arr[right])
{
right++;
flag = !flag;
continue;
}
else if(flag && arr[right+1]<arr[right])
{
right++;
flag = !flag;
continue;
}
break;
}
ans = Math.max(ans, right-left+1);
ind = right;
}
ind++;
}
return ans;
}
}
*/
class Solution {
public int maxTurbulenceSize(int[] arr) {
int inc = 1, dec = 1, maxLen = 1;
for(int i = 1; i<arr.length; i++)
{
if(arr[i-1]<arr[i])
{
inc = 1 + dec;
dec = 1;
}
else if(arr[i-1]>arr[i])
{
dec = 1 + inc;
inc = 1;
}
else
{
inc = 1;
dec = 1;
}
maxLen = Math.max(maxLen, Math.max(inc, dec));
}
return maxLen;
}
}