第二场(B-疯狂过山车)
链接:https://ac.nowcoder.com/acm/contest/6219/B
来源:牛客网
题目描述:
今天牛牛去游乐园玩过山车项目,他觉得过山车在上坡下坡的过程是非常刺激的,回到家之后就受到启发,想到了一个问题。如果把整个过山车的轨道当作是一个长度为n的数组num,那么在过山车上坡时数组中的值是呈现递增趋势的,到了最高点以后,数组中的值呈现递减的趋势,牛牛把符合这样先增后减规律的数组定义为金字塔数组,请你帮牛牛在整个num数组中找出长度最长的金字塔数组,如果金字塔数组不存在,请输出0。
示例输入:
5,[1,5,3,3,1]
示例输出:
3
解题思路:
从示例可以看出,满足要求的子数组必须是先严格递增后严格递减的。我们只需要计算严格递增的子数组长度l,以及紧接其后的严格递减子数组长度r,那么对应的金字塔数组长度就是l+r,更新最大满足条件的长度即可。
代码:
class Solution {
public:
/**
*
* @param n int整型
* @param num int整型vector
* @return int整型
*/
int getMaxLength(int n, vector<int>& num) {
// write code here
int res = 0, l, r, i = 0;
--n;
while(i < n) {
l = r = 0;
while(i < n && num[i] == num[i + 1]) ++i;
while(i < n && num[i] < num[i + 1]) ++i, ++l;
while(i < n && num[i] > num[i + 1]) ++i, ++r;
res = max(res, l + r + 1);
}
return res;
}
};
