题目来源:http://www.lintcode.com/zh-cn/problem/longest-increasing-continuous-subsequence/
题目描述
最长上升连续子序列,给定一个整数数组(下标从 0 到 n-1, n 表示整个数组的规模),请找出该数组中的最长上升连续子序列。(最长上升连续子序列可以定义为从右到左或从左到右的序列。)
如果两个数相等,不算上升
样例:
给定 [5, 4, 2, 1, 3]
, 其最长上升连续子序列(LICS)为 [5, 4, 2, 1]
, 返回 4
.
给定 [5, 1, 2, 3, 4]
, 其最长上升连续子序列(LICS)为 [1, 2, 3, 4]
, 返回 4
.
思路 = 动态规划
因为最长上升连续子序列既可以递增,又可以递减,所以分开计算:
- 最长递增连续子序列;
- 最长递减连续子序列;
code
class Solution {
public:
/**
* @param A an array of Integer
* @return an integer
*/
int longestIncreasingContinuousSubsequence(vector<int>& A) {
// Write your code here
int size = A.size();
if (size <= 1) {
return size;
}
int ret = 1;
int times = 1;
// 递增
for (int i = 1; i < size ; i++) {
if (A[i] > A[i - 1]) { // 递增,长度+1
times++;
ret = max(times, ret);
}
else { // 不递增,重新计算
times = 1;
}
}
// 递减
times = 1;
for (int i = 1; i < size ; i++) {
if (A[i] < A[i - 1]) {
times++;
ret = max(times, ret);
}
else {
times = 1;
}
}
return ret;
}
};
请尊重作者的劳动,转载请注明作者及原文地址(http://blog.csdn.net/lis_12/article/details/55212687).
如果觉得本文对您有帮助,请点击‘顶’支持一下,您的支持是我写作最大的动力,谢谢。