[LintCode] Longest Increasing Continuous subsequence

http://www.lintcode.com/en/problem/longest-increasing-continuous-subsequence/#

Give you an integer array (index from 0 to n-1, where n is the size of this array),find the longest increasing continuous subsequence in this array. (The definition of the longest increasing continuous subsequence here can be from right to left or from left to right)

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问题,直接上代码:

class Solution {
public:
    /**
     * @param A an array of Integer
     * @return  an integer
     */
    int longestIncreasingContinuousSubsequence(vector<int>& A) {
        if (A.empty()) {
            return 0;
        }
        
        int *state = new int[A.size()]();
        
        state[0] = 1;
        for (int ix = 1; ix < A.size(); ix++) {
            if (A[ix] > A[ix - 1]) {
                state[ix] = state[ix - 1] + 1;
            } else {
                state[ix] = 1;
            }
        }
        int leftToRight = *max_element(state, state + A.size());
        
  
        state[0] = 1;
        for (int ix = 1; ix < A.size(); ix++) {
            if (A[ix] < A[ix - 1]) {
                state[ix] = state[ix - 1] + 1;
            } else {
                state[ix] = 1;
            }
        }
        int rightToLeft = *max_element(state, state + A.size());
        
        return max(leftToRight, rightToLeft);
    }
};
posted @ 2015-05-26 11:49  Acjx  阅读(721)  评论(0编辑  收藏  举报