File tree 2 files changed +48
-0
lines changed
2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change 652
652
842|[ Split Array into Fibonacci Sequence] ( ./0842-split-array-into-fibonacci-sequence.js ) |Medium|
653
653
843|[ Guess the Word] ( ./0843-guess-the-word.js ) |Hard|
654
654
844|[ Backspace String Compare] ( ./0844-backspace-string-compare.js ) |Easy|
655
+ 845|[ Longest Mountain in Array] ( ./0845-longest-mountain-in-array.js ) |Medium|
655
656
846|[ Hand of Straights] ( ./0846-hand-of-straights.js ) |Medium|
656
657
867|[ Transpose Matrix] ( ./0867-transpose-matrix.js ) |Easy|
657
658
868|[ Binary Gap] ( ./0868-binary-gap.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 845. Longest Mountain in Array
3
+ * https://leetcode.com/problems/longest-mountain-in-array/
4
+ * Difficulty: Medium
5
+ *
6
+ * You may recall that an array arr is a mountain array if and only if:
7
+ * - arr.length >= 3
8
+ * - There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that:
9
+ * - arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
10
+ * - arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
11
+ *
12
+ * Given an integer array arr, return the length of the longest subarray, which is a
13
+ * mountain. Return 0 if there is no mountain subarray.
14
+ */
15
+
16
+ /**
17
+ * @param {number[] } arr
18
+ * @return {number }
19
+ */
20
+ var longestMountain = function ( arr ) {
21
+ const n = arr . length ;
22
+ if ( n < 3 ) return 0 ;
23
+
24
+ let maxLength = 0 ;
25
+ let i = 1 ;
26
+
27
+ while ( i < n - 1 ) {
28
+ const isPeak = arr [ i ] > arr [ i - 1 ] && arr [ i ] > arr [ i + 1 ] ;
29
+ if ( ! isPeak ) {
30
+ i ++ ;
31
+ continue ;
32
+ }
33
+ let leftBound = i - 1 ;
34
+ while ( leftBound > 0 && arr [ leftBound - 1 ] < arr [ leftBound ] ) {
35
+ leftBound -- ;
36
+ }
37
+ let rightBound = i + 1 ;
38
+ while ( rightBound < n - 1 && arr [ rightBound ] > arr [ rightBound + 1 ] ) {
39
+ rightBound ++ ;
40
+ }
41
+ const mountainLength = rightBound - leftBound + 1 ;
42
+ maxLength = Math . max ( maxLength , mountainLength ) ;
43
+ i = rightBound + 1 ;
44
+ }
45
+
46
+ return maxLength ;
47
+ } ;
You can’t perform that action at this time.
0 commit comments