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.
注意:
這個(gè) for 循環(huán)寫得很精妙:每次循環(huán)羡棵,需要判斷是否符合 increasing的趨勢(shì)河绽,如果符合秸应,則計(jì)數(shù)器加一匀钧,否則讓計(jì)數(shù)器歸一梅鹦。下一個(gè)循環(huán)前,更新 answer鲁豪,即記錄目前符合條件的最長(zhǎng)子串的長(zhǎng)度潘悼。
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;
}
}