当前位置: 面试刷题>> 最长上升连续子序列 (经典算法题500道)


题目描述补充

题目:最长上升连续子序列(Longest Increasing Continuous Subsequence, LICS)

给定一个未排序的整数数组,找到其中最长上升连续子序列的长度。注意,这里的子序列是原数组中的一系列元素(不一定连续),但必须是连续递增的。即,如果序列中的第i个元素小于第i+1个元素,则称这两个元素是连续的。

示例

输入数组: [10, 9, 2, 5, 3, 7, 101, 18]

输出: 4

解释: 最长的上升连续子序列是 [2, 5, 3, 7],它的长度为 4。

PHP 代码示例

function lengthOfLICS($nums) {
    if (empty($nums)) return 0;
    
    $maxLength = 1;
    $currentLength = 1;
    
    for ($i = 1; $i < count($nums); $i++) {
        if ($nums[$i] > $nums[$i - 1]) {
            $currentLength++;
            $maxLength = max($maxLength, $currentLength);
        } else {
            $currentLength = 1;
        }
    }
    
    return $maxLength;
}

// 测试
$nums = [10, 9, 2, 5, 3, 7, 101, 18];
echo lengthOfLICS($nums); // 输出 4

Python 代码示例

def lengthOfLICS(nums):
    if not nums:
        return 0
    
    maxLength = 1
    currentLength = 1
    
    for i in range(1, len(nums)):
        if nums[i] > nums[i-1]:
            currentLength += 1
            maxLength = max(maxLength, currentLength)
        else:
            currentLength = 1
    
    return maxLength

# 测试
nums = [10, 9, 2, 5, 3, 7, 101, 18]
print(lengthOfLICS(nums))  # 输出 4

JavaScript 代码示例

function lengthOfLICS(nums) {
    if (nums.length === 0) return 0;
    
    let maxLength = 1;
    let currentLength = 1;
    
    for (let i = 1; i < nums.length; i++) {
        if (nums[i] > nums[i - 1]) {
            currentLength++;
            maxLength = Math.max(maxLength, currentLength);
        } else {
            currentLength = 1;
        }
    }
    
    return maxLength;
}

// 测试
let nums = [10, 9, 2, 5, 3, 7, 101, 18];
console.log(lengthOfLICS(nums)); // 输出 4

码小课网站中有更多关于算法和数据结构的内容分享,包括不同编程语言实现的多种算法问题解答,欢迎大家学习交流。

推荐面试题