#1218 Longest Arithmetic Subsequence of Given Difference

该博客介绍了一种解决寻找给定整数数组中最长等差子序列长度的方法。使用动态规划策略,通过一个哈希映射存储以每个元素结尾的最长等差子序列的长度,并更新最大值。代码示例展示了如何实现这一算法,对于给定的数组和差值,返回最长等差子序列的长度。
摘要由CSDN通过智能技术生成

Description

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.

A subsequence is a sequence that can be derived from arr by deleting some or no elements without changing the order of the remaining elements.

Examples

Example 1:

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

Example 2:

Input: arr = [1,3,5,7], difference = 1
Output: 1
Explanation: The longest arithmetic subsequence is any single element.

Example 3:

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

Constraints:

1 <= arr.length <= 1 0 5 10^5 105
− 1 0 4 -10^4 104 <= arr[i], difference <= 1 0 4 10^4 104

思路

用dp,但是dp[i]存的是以i为结尾的maxSubSequence,所以用map存

代码

class Solution {
    public int longestSubsequence(int[] arr, int difference) {
        Map<Integer, Integer> dp = new HashMap<>();
        int max = 0;
        
        for (int a: arr) {
            int count = dp.getOrDefault(a - difference, 0) + 1;
            max = Math.max(count, max);
            dp.put(a, Math.max(dp.getOrDefault(a - difference, 0), count));
        }
        
        return max;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值