Longest Arithmetic Subsequence

Medium

Description

Given an integer array nums, return the length of the longest arithmetic subsequence. An arithmetic sequence has constant difference.

Examples

Input:nums = [3,6,9,12]
Output:4
Explanation:

Difference 3 throughout.

Input:nums = [1,7,9,4]
Output:3
Explanation:

The longest arithmetic subsequence has length 3. One such subsequence is [1,4,7] (not all present) — checking all pairs: differences include 6(1→7), 3(1→4), 2(7→9), -5(9→4). The subsequence [1,4,7] requires 7 at index 2, giving [1,7,?] or [4,9,?]. The longest with common difference is length 3.

Input:nums = [2,4,6,8,10]
Output:5
Explanation:

The entire array forms an arithmetic sequence with a common difference of 2: [2,4,6,8,10]. Since all elements maintain the same difference, the longest arithmetic subsequence is the entire array with length 5.

Constraints

  • 2 ≤ nums.length ≤ 1000

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!