forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0978-longest-turbulent-subarray.kt
30 lines (30 loc) · 1.13 KB
/
0978-longest-turbulent-subarray.kt
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
class Solution {
fun maxTurbulenceSize(arr: IntArray): Int {
if (arr.size == 1) return 1
var previousEqualitySymbol = ' '
var currentSubArraySize = 1
var maxSubArraySize = 1
for (i in 1..arr.lastIndex) {
if (arr[i - 1] > arr[i] && previousEqualitySymbol != '>') {
currentSubArraySize++
maxSubArraySize = maxOf(maxSubArraySize, currentSubArraySize)
previousEqualitySymbol = '>'
continue
}
if (arr[i - 1] < arr[i] && previousEqualitySymbol != '<') {
currentSubArraySize++
maxSubArraySize = maxOf(maxSubArraySize, currentSubArraySize)
previousEqualitySymbol = '<'
continue
}
currentSubArraySize = if (arr[i - 1] == arr[i]) 1 else 2
maxSubArraySize = maxOf(maxSubArraySize, currentSubArraySize)
previousEqualitySymbol = when {
arr[i - 1] < arr[i] -> '<'
arr[i - 1] > arr[i] -> '>'
else -> ' '
}
}
return maxSubArraySize
}
}