Longest Arithmetic Subsequence

Given an array nums of integers, return the length of the longest arithmetic subsequence in nums.

Note that:

  • A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
  • A sequence seq is arithmetic if seq[i + 1] - seq[i] are all the same value for 0 <= i < seq.length - 1.
Example 1
Inputnums = [3,6,9,12]
Output4
The whole array is an arithmetic sequence with steps of length 3.
Example 2
Inputnums = [9,4,7,2,10]
Output3
The longest arithmetic subsequence is [4,7,10].

Constraints

  • 2 <= nums.length <= 1000
  • 0 <= nums[i] <= 500

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate