Skip to content

Commit 9e1ee64

Browse files
committed
Add solution #978
1 parent 4e93b8c commit 9e1ee64

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,059 LeetCode solutions in JavaScript
1+
# 1,060 LeetCode solutions in JavaScript
22

33
[https://leetcode.com/](https://leetcode.com/)
44

@@ -786,6 +786,7 @@
786786
975|[Odd Even Jump](./solutions/0975-odd-even-jump.js)|Hard|
787787
976|[Largest Perimeter Triangle](./solutions/0976-largest-perimeter-triangle.js)|Easy|
788788
977|[Squares of a Sorted Array](./solutions/0977-squares-of-a-sorted-array.js)|Easy|
789+
978|[Longest Turbulent Subarray](./solutions/0978-longest-turbulent-subarray.js)|Medium|
789790
985|[Sum of Even Numbers After Queries](./solutions/0985-sum-of-even-numbers-after-queries.js)|Easy|
790791
989|[Add to Array-Form of Integer](./solutions/0989-add-to-array-form-of-integer.js)|Easy|
791792
994|[Rotting Oranges](./solutions/0994-rotting-oranges.js)|Medium|
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 978. Longest Turbulent Subarray
3+
* https://leetcode.com/problems/longest-turbulent-subarray/
4+
* Difficulty: Medium
5+
*
6+
* Given an integer array arr, return the length of a maximum size turbulent subarray of arr.
7+
*
8+
* A subarray is turbulent if the comparison sign flips between each adjacent pair of elements
9+
* in the subarray.
10+
*
11+
* More formally, a subarray [arr[i], arr[i + 1], ..., arr[j]] of arr is said to be turbulent
12+
* if and only if:
13+
* - For i <= k < j:
14+
* - arr[k] > arr[k + 1] when k is odd, and
15+
* - arr[k] < arr[k + 1] when k is even.
16+
* - Or, for i <= k < j:
17+
* - arr[k] > arr[k + 1] when k is even, and
18+
* - arr[k] < arr[k + 1] when k is odd.
19+
*/
20+
21+
/**
22+
* @param {number[]} arr
23+
* @return {number}
24+
*/
25+
var maxTurbulenceSize = function(arr) {
26+
let result = 1;
27+
let inc = 1;
28+
let dec = 1;
29+
30+
for (let i = 1; i < arr.length; i++) {
31+
if (arr[i] > arr[i - 1]) {
32+
inc = dec + 1;
33+
dec = 1;
34+
} else if (arr[i] < arr[i - 1]) {
35+
dec = inc + 1;
36+
inc = 1;
37+
} else {
38+
inc = 1;
39+
dec = 1;
40+
}
41+
result = Math.max(result, inc, dec);
42+
}
43+
44+
return result;
45+
};

0 commit comments

Comments
 (0)