Longest Arithmetic Subsequence

MediumDynamic Programming2d dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an integer array nums. Pick a subsequence (delete zero or more elements without reordering the rest) in which every pair of neighbouring elements differs by the same amount. That common difference may be positive, negative, or zero. Return the length of the longest such arithmetic subsequence. Because nums has at least two elements, any two elements already form an arithmetic subsequence, so the answer is always at least 2. Aim for roughly O(n^2) time.

Examples

Input: nums = [3,6,9,12]
Output: 4
The whole array has common difference 3.
Input: nums = [9,4,7,2,10]
Output: 3
[4,7,10] has common difference 3.
Input: nums = [20,1,15,3,10,5,8]
Output: 4
[20,15,10,5] has common difference -5.

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More 2d dp problems