#1027
Longest Arithmetic Subsequence
specialist · 870 · lc medium +31 · verified · 49.9% accepted · 4,905 likes · top 37%
Description
Given an integer array nums, return the length of the longest arithmetic subsequence in nums.
- A subsequence is derived by deleting some (or no) elements without changing the order of the rest.
- A sequence is arithmetic if consecutive differences seq[i+1] - seq[i] are all equal.
Example 1:
Input: nums = [3,6,9,12]
Output: 4
Explanation: The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: nums = [9,4,7,2,10]
Output: 3
Explanation: The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: nums = [20,1,15,3,10,5,8]
Output: 4
Explanation: The longest arithmetic subsequence is [20,15,10,5].
Code
1
2
3