Longest Arithmetic Subsequence

Given an array nums of integers, return the length of the longest arithmetic subsequence in nums. A subsequence keeps the original order but may skip elements, and a sequence is arithmetic when every pair of neighbours differs by the same value.

30:00

Longest Arithmetic Subsequence
medium
Free written solution
Topics
Companies

Given an array nums of integers, return the length of the longest arithmetic subsequence in nums. A subsequence keeps the original order but may skip elements, and a sequence is arithmetic when every pair of neighbours differs by the same value.

Example 1:
Input: {"nums":[3,6,9,12]}
Output: 4
Constraints:
  • 2≤nums.length≤10002 \leq \text{nums.length} \leq 1000

  • 0≤nums[i]≤5000 \leq \text{nums}[i] \leq 500

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[3,6,9,12]}

Give every index its own map dp[j]: difference -> length of the longest arithmetic run ending at j with that step. Any two numbers already form a run of 2, so best starts at 2.

nums

best = 2

3

0

6

1

9

2

12

3

dp[k]: step d → length of the longest run with that step ending at k

dp[0] (3)

nothing before

dp[1] (6)

empty

dp[2] (9)

empty

dp[3] (12)

empty

Variables
VariableValue
n4
best2
DepthFunction Call
Stack empty
0/12