Longest Arithmetic Subsequence — LeetCode 1027 Python Solution
- Problem
- #1027
- Pattern
- Binary Search
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- nums = [3,6,9,12]
- Output
- 4
- Explanation
- The whole array is an arithmetic sequence with steps of length = 3.
Python solution
class Solution:
def longestArithSeqLength(self, nums: List[int]) -> int:
n = len(nums)
f = [[1] * 1001 for _ in range(n)]
ans = 0
for i in range(1, n):
for k in range(i):
j = nums[i] - nums[k] + 500
f[i][j] = max(f[i][j], f[k][j] + 1)
ans = max(ans, f[i][j])
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times (d + n)) |
| Space | O(n \times d) auxiliary |
Pattern: Binary Search
Halve the search space each step — over an array, or over the answer itself. LeetCode 1027. Longest Arithmetic Subsequence is filed here because LeetCode tags it Binary Search, which is the vocabulary this hub collects.
The binary search guide has the Python template for the pattern and the 254 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1027. Longest Arithmetic Subsequence?
- LeetCode 1027. Longest Arithmetic Subsequence is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1027. Longest Arithmetic Subsequence?
- The Python solution on this page runs in O(n \times (d + n)).
- What is the space complexity of LeetCode 1027. Longest Arithmetic Subsequence?
- The Python solution on this page uses O(n \times d) auxiliary space.
- What topics does LeetCode 1027. Longest Arithmetic Subsequence cover?
- LeetCode 1027. Longest Arithmetic Subsequence is tagged Array, Hash Table, Binary Search and Dynamic Programming on LeetCode.