#397 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.

题目思路:

这题用了一点dp的思想:用local来记录小范围内的增长/减少subarray的长度,如果local_inc遇到减少的情况,就reset成1;用global来记录最长的长度,取自己和local的max。

Mycode(AC = 22ms):

class Solution {
public:
    /**
     * @param A an array of Integer
     * @return  an integer
     */
    int longestIncreasingContinuousSubsequence(vector& A) {
        // Write your code here
        int local_inc = 1, local_dec = 1;
        int global_inc = 1, global_dec = 1;
        
        if (A.size() <= 2) return A.size();
        
        // local_inc to record locally max increasing length
        // local_dec to record locally max decreasing length
        for (int i = 1; i < A.size(); i++) {
            if (A[i] >= A[i - 1]) {
                local_inc++;
                global_inc = max(global_inc, local_inc);
                local_dec = 1;
            }
            else {
                local_dec++;
                global_dec = max(global_dec, local_dec);
                local_inc = 1;
            }
        }
        
        return max(global_inc, global_dec);
    }
};


你可能感兴趣的:(lintcode)