问题描述:
845. 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 thatB[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 array A
of integers, return the length of the longest mountain.
Return 0
if 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:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
- Can you solve it using only one pass?
- Can you solve it in
O(1)
space?
解题思路:
我们可以用变量来标识是否出现峰值,以及出现峰值的最左边的下标
对于A[i] > A[i-1] ; A[i] < A[i-1]; A[i] == A[i-1]分别讨论。
1.A[i] > A[i-1]:
此时为上坡情景,注意首先出现时,要改变是否出现峰值的标志位和最左边界
2.A[i] < A[i-1]:
此时为下坡,可能会出现在一开始的场景,所以我们在对ret进行更新的时候,要注意峰值标志位以及最左边界是否是有效值。
3.A[i] == A[i-1]
一定要检查这种情况,若出现连续相同的值,则当前不管是上坡下坡还是与峰值同大,都将无效:设置l = -1, peak = -1;
代码:
class Solution { public: int longestMountain(vector<int>& A) { int l = -1,ret = 0, peak = -1; for(int r = 1; r < A.size(); r++){ if(A[r] > A[r-1]){ if(peak != -1 || l == -1){ peak = -1; l = r-1; } }else if(A[r] < A[r-1]){ if(l != -1){ if(peak == -1) peak = 0; ret = max(ret, r-l+1); } }else{ l = -1; peak = -1; } } return ret; } };