LeetCode 题解工作台

最长定差子序列

给你一个整数数组 arr 和一个整数 difference ,请你找出并返回 arr 中最长等差子序列的长度,该子序列中相邻元素之间的差等于 difference 。 子序列 是指在不改变其余元素顺序的情况下,通过删除一些元素或不删除任何元素而从 arr 派生出来的序列。 示例 1: 输入: arr…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

我们可以使用哈希表 来存储以 结尾的最长等差子序列的长度。 遍历数组 ,对于每个元素 ,我们更新 为 $f[x - \textit{difference}] + 1$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 arr 和一个整数 difference,请你找出并返回 arr 中最长等差子序列的长度,该子序列中相邻元素之间的差等于 difference

子序列 是指在不改变其余元素顺序的情况下,通过删除一些元素或不删除任何元素而从 arr 派生出来的序列。

 

示例 1:

输入:arr = [1,2,3,4], difference = 1
输出:4
解释:最长的等差子序列是 [1,2,3,4]。

示例 2:

输入:arr = [1,3,5,7], difference = 1
输出:1
解释:最长的等差子序列是任意单个元素。

示例 3:

输入:arr = [1,5,7,8,5,3,4,2,1], difference = -2
输出:4
解释:最长的等差子序列是 [7,5,3,1]。

 

提示:

  • 1 <= arr.length <= 105
  • -104 <= arr[i], difference <= 104
lightbulb

解题思路

方法一:动态规划

我们可以使用哈希表 ff 来存储以 xx 结尾的最长等差子序列的长度。

遍历数组 arr\textit{arr},对于每个元素 xx,我们更新 f[x]f[x]f[xdifference]+1f[x - \textit{difference}] + 1

遍历结束后,我们返回 ff 中的最大值作为答案返回即可。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为数组 arr\textit{arr} 的长度。

1
2
3
4
5
6
7
class Solution:
    def longestSubsequence(self, arr: List[int], difference: int) -> int:
        f = defaultdict(int)
        for x in arr:
            f[x] = f[x - difference] + 1
        return max(f.values())
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate should demonstrate familiarity with dynamic programming techniques.

  • question_mark

    They should understand how hash tables are used to optimize subsequence tracking.

  • question_mark

    The candidate must ensure they can explain the trade-offs between time and space complexity in this approach.

warning

常见陷阱

外企场景
  • error

    Forgetting to account for negative differences when scanning the array.

  • error

    Overcomplicating the problem by trying to brute force through all possible subsequences.

  • error

    Not using hash tables efficiently, leading to unnecessary recomputation or slower performance.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider variations where the difference is zero, which means the subsequence would consist of identical elements.

  • arrow_right_alt

    Explore scenarios where elements of the array are all unique but can form an arithmetic subsequence with a given difference.

  • arrow_right_alt

    Test with arrays that have negative and positive numbers mixed, making sure the algorithm handles both directions of differences.

help

常见问题

外企场景

最长定差子序列题解:数组·哈希·扫描 | LeetCode #1218 中等