397. Longest Continuous Increasing Subsequence

本文探讨了如何在整数数组中寻找最长的连续递增子序列,提供了一种遍历数组并维护最大递增和递减计数的高效算法,通过两个计数器分别跟踪递增和递减序列长度,最终返回两者之间的最大值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. Longest Continuous Increasing 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.
Example
Example 1:

Input: [5, 4, 2, 1, 3]
Output: 4
Explanation:
For [5, 4, 2, 1, 3], the LICS is [5, 4, 2, 1], return 4.
Example 2:

Input: [5, 1, 2, 3, 4]
Output: 4
Explanation:
For [5, 1, 2, 3, 4], the LICS is [1, 2, 3, 4], return 4.
Challenge
O(n) time and O(1) extra space.

解法1:
我的方法是遍历数组,遇到上升序列就累加IncrCount并维护maxIncrCount, 同时DecrCount变成1。同样,遇到下降序列就累加DecrCount并维护maxDecrCount,同时IncrCount变成1。
注意是变成1而不是变成0,因为一个数也算一个序列。
注意,这题跟LintCode 76 Longest Increasing Subsequence那题不一样,LintCode 76 是经典的LIS,只能用DP或单调队列。

class Solution {
public:
    /**
     * @param A: An array of Integer
     * @return: an integer
     */
    int longestIncreasingContinuousSubsequence(vector<int> &A) {
        int len = A.size();
        if (len == 0) return 0;
        int incrCount = 1, maxIncrCount = 1;
        int decrCount = 1, maxDecrCount = 1;
        
        for (int i = 1; i < len; ++i) {
            if (A[i] > A[i - 1]) {
                decrCount = 1;
                incrCount++;
                maxIncrCount = max(maxIncrCount, incrCount);
            } else if (A[i] < A[i - 1]){
                incrCount = 1;
                decrCount++;
                maxDecrCount = max(maxDecrCount, decrCount);
            } else {
                incrCount = 1;
                decrCount = 1;
            }
        }
        
        return max(maxIncrCount, maxDecrCount);
    }
};

解法2: DP?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值