Longest Mountain in Array
Let's call any (contiguous) subarray B (of A) a_mountain_if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1](Note that B could be any subarray of A, including the entire array A.)
Given an arrayA of integers, return the length of the longest mountain.
Return0if there is no mountain.
Example 1:
Input:
[2,1,4,7,3,2,5]
Output:
5
Explanation:
The largest mountain is [1,4,7,3,2] which has length 5.Example 2:
Input:
[2,2,2]
Output:
0
Explanation:
There is no mountain.Note:
Follow up:
Can you solve it using only one pass?
Can you solve it in
O(1)space?
分析
可以forward backward遍历,2个数组up and down,最后遍历一遍相加。反向遍历也是按照递增来做
或者直接up,down2个变量,一次遍历,遇到不合条件:1 down>0 and 开始增加 2 ==
起始点为0,高/低一个就加1
Last updated
Was this helpful?