|
| 1 | +/** |
| 2 | + * Two Pointers | Greedy |
| 3 | + * Time O(n) | Space O(1) |
| 4 | + * https://leetcode.com/problems/longest-turbulent-subarray/ |
| 5 | + * @param {number[]} arr |
| 6 | + * @return {number} |
| 7 | + */ |
| 8 | +var maxTurbulenceSize = function(arr) { |
| 9 | + |
| 10 | + const higherAndLower = (start) => { |
| 11 | + |
| 12 | + let i = start; |
| 13 | + let shouldBeLow = true; |
| 14 | + |
| 15 | + while(i + 1 < arr.length) { |
| 16 | + if(shouldBeLow && arr[i+1] > arr[i]) break; |
| 17 | + if(!shouldBeLow && arr[i+1] < arr[i]) break; |
| 18 | + if(arr[i+1] === arr[i]) break; |
| 19 | + shouldBeLow = !shouldBeLow; |
| 20 | + i++; |
| 21 | + } |
| 22 | + |
| 23 | + return i; |
| 24 | + |
| 25 | + } |
| 26 | + |
| 27 | + const lowerAndHigher = (start) => { |
| 28 | + |
| 29 | + |
| 30 | + let i = start; |
| 31 | + let shouldBeHigh = true; |
| 32 | + |
| 33 | + while(i + 1 < arr.length) { |
| 34 | + if(shouldBeHigh && arr[i+1] < arr[i]) break; |
| 35 | + if(!shouldBeHigh && arr[i+1] > arr[i]) break; |
| 36 | + if(arr[i+1] === arr[i]) break; |
| 37 | + shouldBeHigh = !shouldBeHigh; |
| 38 | + i++; |
| 39 | + } |
| 40 | + |
| 41 | + return i; |
| 42 | + } |
| 43 | + |
| 44 | + |
| 45 | + let left = 0; |
| 46 | + let right = 1; |
| 47 | + let max = 1; |
| 48 | + |
| 49 | + while(right < arr.length) { |
| 50 | + |
| 51 | + if(arr[left] > arr[right]) { |
| 52 | + right = higherAndLower(left); |
| 53 | + max = Math.max(right-left+1, max); |
| 54 | + left = right; |
| 55 | + right = right+1; |
| 56 | + continue; |
| 57 | + } |
| 58 | + |
| 59 | + if(arr[left] < arr[right]) { |
| 60 | + right = lowerAndHigher(left); |
| 61 | + max = Math.max(right-left+1, max); |
| 62 | + left = right; |
| 63 | + right = right+1; |
| 64 | + continue; |
| 65 | + } |
| 66 | + |
| 67 | + if(arr[left] === arr[right]) { |
| 68 | + left++; |
| 69 | + right++; |
| 70 | + } |
| 71 | + |
| 72 | + } |
| 73 | + |
| 74 | + return max; |
| 75 | +}; |
0 commit comments