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.
** Notice
O(n) time and O(1) extra space.
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.
注意:
这个 for 循环写得很精妙:每次循环,需要判断是否符合 increasing的趋势,如果符合,则计数器加一,否则让计数器归一。下一个循环前,更新 answer,即记录目前符合条件的最长子串的长度。
public class Solution {
/**
* @param A an array of Integer
* @return an integer
*/
public int longestIncreasingContinuousSubsequence(int[] A) {
// Write your code here
if (A.length <= 1) return A.length;
int answer = 1;
int n = A.length;
int length = 1;
// from left to right
for (int i = 1; i < n; i++) {
if (A[i] > A[i - 1]) {
length++;
} else {
length = 1;
}
answer = Math.max(answer, length);
}
length = 1;
// from right to left
for (int i = n - 2; i >= 0; i--) {
if (A[i] > A[i+1]) {
length++;
} else {
length = 1;
}
answer = Math.max(answer, length);
}
return answer;
}
}