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 循環(huán)寫得很精妙:每次循環(huán),需要判斷是否符合 increasing的趨勢,如果符合,則計數(shù)器加一,否則讓計數(shù)器歸一。下一個循環(huán)前,更新 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;
}
}