Monday, May 2, 2016

[LintCode] 397 Longest Increasing Continuous Subsequence 解题报告

Description
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.


思路
从前往后分别过两次。第一次统计递增,第二次统计递减。选最大值返回。


Code
public class Solution {
    /**
     * @param A an array of Integer
     * @return  an integer
     */
    public int longestIncreasingContinuousSubsequence(int[] A) {
        // Write your code here
        if (A == null || A.length == 0) {
            return 0;
        }
        if (A.length == 1) {
            return 1;
        }
        int max = Integer.MIN_VALUE;
        int count = 1;
        for (int i = 1; i < A.length; i++) {
            if (A[i] > A[i - 1]) {
                count++;
            }
            else {
                count = 1;
            }
            max = Math.max(max, count);
        }
        count = 1;
        for (int i = 1; i < A.length; i++) {
            if (A[i] < A[i - 1]) {
                count++;
            }
            else {
                count = 1;
            }
            max = Math.max(max, count);
        }
        return max;
    }
}