原题链接在这里:http://www.lintcode.com/en/problem/longest-increasing-continuous-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.
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
.
题解:
从左向右 若连续递增 就更新 len, 再从右向左 若连续递增 就更新res.
Time Complexity: O(n). Space: O(1).
AC Java:
1 public class Solution { 2 public int longestIncreasingContinuousSubsequence(int[] A) { 3 if(A == null || A.length == 0){ 4 return 0; 5 } 6 7 int res = 1; 8 int len = 1; 9 for(int i = 1; i<A.length; i++){ 10 if(A[i] > A[i-1]){ 11 len++; 12 }else{ 13 len = 1; 14 } 15 res = Math.max(res, len); 16 } 17 18 len = 1; 19 for(int i = A.length-2; i>=0; i--){ 20 if(A[i] > A[i+1]){ 21 len++; 22 }else{ 23 len = 1; 24 } 25 res = Math.max(res, len); 26 } 27 28 return res; 29 } 30 }