Leetcode-1218. Longest Arithmetic Subsequence of Given Difference 最长定差子序列 (DP)

题目

给你一个整数数组 arr 和一个整数 difference,请你找出 arr 中所有相邻元素之间的差等于给定 difference 的等差子序列,并返回其中最长的等差子序列的长度。
链接:https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/

Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.

Example:

Input: arr = [1,2,3,4], difference = 1
Output: 4
Explanation: The longest arithmetic subsequence is [1,2,3,4].

思路及代码

DP

  • dict[i]:到数字i时,最长的等差子序列的长度;用key, value来分别记录数字和到这个数字为止最长的序列长度
  • dict[i] = dict[i-diff] + 1:找跟当前数字相差diff的上一数字,然后count+1
# 568ms 89.31%
class Solution:
    def longestSubsequence(self, arr: List[int], difference: int) -> int:
        c_dict = {}
        for i in range(len(arr)):
            prev = arr[i] - difference
            if prev in c_dict:
                c_dict[arr[i]] = c_dict[prev] + 1
            else:
                c_dict[arr[i]] = 1
        return max(c_dict.values())

复杂度

T = O ( n ) O(n) O(n)
S = O ( n ) O(n) O(n)

你可能感兴趣的:(Leetcode,leetcode,动态规划,算法,python)