845. Longest Mountain in Array

题目

https://leetcode.com/problems/longest-mountain-in-array/description/

-w949

想法

描述清楚不难,但是用一个巧妙简洁的方式叙述出来,可就没有那么容易了

蛮有趣的一个题目

答案

借鉴自:
https://leetcode.com/problems/longest-mountain-in-array/discuss/135593/C++JavaPython-1-pass-and-O(1)-space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int longestMountain(vector<int>& A) {
int up = 0, down = 0;
int res = 0;
for (int i = 1; i < A.size(); i++) {
if (down && A[i] > A[i - 1] || A[i] == A[i - 1])
up = down = 0;
if (A[i] > A[i - 1])
up++;
else if (A[i] < A[i - 1])
down++;
if (up && down)
res = max(res, up + down + 1);
}
return res;
}
};