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
For [5, 4, 2, 1, 3]
, the LICS is [5, 4, 2, 1]
, return 4
.
For [5, 1, 2, 3, 4]
, the LICS is [1, 2, 3, 4]
, return 4
.
设置flag储存当前升序或者降序。当升序序列改为降序时更新最大长度并初始化maxLen。注意此时maxLen长度为2.
题目要求:O(n) time and O(1) extra space.
public class Solution {
/**
* @param A an array of Integer
* @return an integer
*/
public int longestIncreasingContinuousSubsequence(int[] A) {
if(A.length == 0) return 0;
int maxLen = 1;
int res = 0;
int incr = 0;
for(int i = 1; i < A.length; i++) {
if(A[i] > A[i - 1]) {
if(incr == 1 || incr == 0) {
maxLen ++;
incr = 1;
}
else {
res = Math.max(res, maxLen);
maxLen = 2;
incr = 1;
}
}
if(A[i] < A[i - 1]) {
if(incr == -1 || incr == 0) {
maxLen ++;
incr = -1;
}
else {
res = Math.max(res, maxLen);
maxLen = 2;
incr = -1;
}
}
}
return Math.max(res, maxLen);
}
}