Skip to main content
Back to problems
#1218
Medium Algorithms

Longest arithmetic subsequence of given difference

Array Hash Table Dynamic Programming
54.3% acceptance
Feb 25, 2026
3375
92
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn longest_subsequence(arr: Vec<i32>, difference: i32) -> i32 {
    use std::collections::HashMap;
    let mut dp: HashMap<i32, i32> = HashMap::new();
    let mut ans = 0;
    for x in arr {
      let prev = dp.get(&(x - difference)).copied().unwrap_or(0);
      let entry = dp.entry(x).or_insert(0);
      *entry = (*entry).max(prev + 1);
      ans = ans.max(*entry);
    }
    ans
  }
}