Article Directory
1. Title
https://tianchi.aliyun.com/oj/118289365933779217/122647324212270018
Description:
Give you a sequence of length n, in his sequence so that you find in a valley sequence, sequence valley is defined as:
- The length of the sequence is even.
- Assume that the length of the subsequence is 2n. Then the first n numbers are strictly decreasing , and the last n numbers are strictly increasing , and the last element of the first paragraph is the same as the first element of the second paragraph, which is also the minimum value in this sequence.
Now I want you to find the longest length that satisfies the valley sequence rule among all subsequences ?
示例
样例 1:
输入: num = [5,4,3,2,1,2,3,4,5]
输出: 8
样例解释:
最长山谷序列为[5,4,3,2,2,3,4,5]
样例 2:
输入: num = [1,2,3,4,5]
输出: 0
样例解释:
不存在山谷序列
2. Problem solving
class Solution {
public:
/**
* @param num: sequence
* @return: The longest valley sequence
*/
int valley(vector<int> &num) {
// write your code here
int n = num.size();
if(n <= 1) return 0;
vector<int> up(n, 1), down(n, 1);//最长递增/递减数组
for(int i = 1, j; i < n; i++) //正序
{
for(j = 0; j < i; j++)
{
if(num[j] > num[i])//前面的比当前大,递减
down[i] = max(down[i], down[j] + 1);
}
}
for(int i = n-2, j; i >= 0; i--) //逆序遍历
{
for(j = i+1; j < n; j++)
{
if(num[j] > num[i])//后面的比当前大,递增
up[i] = max(up[i], up[j] + 1);
}
}
int maxlen = 0;
for(int i = 0, j; i < n; i++)
{
for(j = i+1; j < n; j++)
{
if(num[i] == num[j])//最小的数
{
maxlen = max(maxlen, min(down[i],up[j])*2);
} // 两侧等长的递减 递增
}
}
return maxlen;
}
};
Time complexity O (n 2) O(n^2)O ( n2)
My CSDN blog address https://michael.blog.csdn.net/
Long press or scan the QR code to follow my official account (Michael Amin), come on together, learn and make progress together!