- Longest Continuous Increasing Subsequence
Give an integer array,find the longest increasing continuous subsequence in this array.
An increasing continuous subsequence:
Can be from right to left or from left to right.
Indices of the integers in the subsequence should be continuous.
Example
Example 1:
Input: [5, 4, 2, 1, 3]
Output: 4
Explanation:
For [5, 4, 2, 1, 3], the LICS is [5, 4, 2, 1], return 4.
Example 2:
Input: [5, 1, 2, 3, 4]
Output: 4
Explanation:
For [5, 1, 2, 3, 4], the LICS is [1, 2, 3, 4], return 4.
Challenge
O(n) time and O(1) extra space.
解法1:
我的方法是遍历数组,遇到上升序列就累加IncrCount并维护maxIncrCount, 同时DecrCount变成1。同样,遇到下降序列就累加DecrCount并维护maxDecrCount,同时IncrCount变成1。
注意是变成1而不是变成0,因为一个数也算一个序列。
注意,这题跟LintCode 76 Longest Increasing Subsequence那题不一样,LintCode 76 是经典的LIS,只能用DP或单调队列。
class Solution {
public:
/**
* @param A: An array of Integer
* @return: an integer
*/
int longestIncreasingContinuousSubsequence(vector<int> &A) {
int len = A.size();
if (len == 0) return 0;
int incrCount = 1, maxIncrCount = 1;
int decrCount = 1, maxDecrCount = 1;
for (int i = 1; i < len; ++i) {
if (A[i] > A[i - 1]) {
decrCount = 1;
incrCount++;
maxIncrCount = max(maxIncrCount, incrCount);
} else if (A[i] < A[i - 1]){
incrCount = 1;
decrCount++;
maxDecrCount = max(maxDecrCount, decrCount);
} else {
incrCount = 1;
decrCount = 1;
}
}
return max(maxIncrCount, maxDecrCount);
}
};
解法2: DP?