LeetCode 题解工作台

最长相邻绝对差递减子序列

给你一个整数数组 nums 。 你的任务是找到 nums 中的 最长 子序列 seq ,这个子序列中相邻元素的 绝对差 构成一个 非递增 整数序列。换句话说, nums 中的序列 seq 0 , seq 1 , seq 2 , ..., seq m 满足 |seq 1 - seq 0 | >= |s…

category

2

题型

code_blocks

0

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums 。

你的任务是找到 nums 中的 最长 子序列 seq ,这个子序列中相邻元素的 绝对差 构成一个 非递增 整数序列。换句话说,nums 中的序列 seq0, seq1, seq2, ..., seqm 满足 |seq1 - seq0| >= |seq2 - seq1| >= ... >= |seqm - seqm - 1| 。

请你返回这个子序列的长度。

 

示例 1:

输入:nums = [16,6,3]

输出:3

解释:

最长子序列是 [16, 6, 3] ,相邻绝对差值为 [10, 3] 。

示例 2:

输入:nums = [6,5,3,4,2,1]

输出:4

解释:

最长子序列是 [6, 4, 2, 1] ,相邻绝对差值为 [2, 2, 1] 。

示例 3:

输入:nums = [10,20,10,19,10,20]

输出:5

解释:

最长子序列是 [10, 20, 10, 19, 10] ,相邻绝对差值为 [10, 10, 9, 9] 。

 

提示:

  • 2 <= nums.length <= 104
  • 1 <= nums[i] <= 300
lightbulb

解题思路

方法一

1
2

speed

复杂度分析

指标
时间complexity depends on the final approach, but a typical solution would run in O(n^2), where n is the length of the input array. Space complexity can be reduced to O(n) if we optimize the storage of subsequence lengths.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Ability to apply dynamic programming effectively.

  • question_mark

    Understanding of the relationship between adjacent differences and subsequence patterns.

  • question_mark

    Skill in optimizing space complexity while maintaining correct results.

warning

常见陷阱

外企场景
  • error

    Forgetting to properly handle the non-increasing condition for differences.

  • error

    Incorrectly updating the subsequence lengths during the iteration.

  • error

    Over-complicating the solution and not reducing the space complexity.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Problem with different constraints on the array length or value range.

  • arrow_right_alt

    Variant where the subsequence must have an exact difference pattern rather than a non-increasing one.

  • arrow_right_alt

    Challenge where the input array contains negative numbers or zero, requiring adjustments to the difference calculation.

help

常见问题

外企场景

最长相邻绝对差递减子序列题解:状态·转移·动态规划 | LeetCode #3409 中等