|
| 1 | +from typing import List |
| 2 | +""" |
| 3 | +Longest Arithmetic Subsequence Problem: Given an array nums of integers, return the length of the longest arithmetic subsequence in nums. |
| 4 | +
|
| 5 | +Note that: |
| 6 | +- A subsequence is an array that can be derived from another array by deleting some or no elements |
| 7 | + without changing the order of the remaining elements. |
| 8 | +- A sequence seq is arithmetic if seq[i + 1] - seq[i] are all the same value (for 0 <= i < seq.length - 1). |
| 9 | +""" |
| 10 | + |
| 11 | +def longest_arithmetic_subsequence(nums: List[int]) -> int: |
| 12 | + """ |
| 13 | + Finds the length of the longest arithmetic subsequence in a given array of integers. |
| 14 | +
|
| 15 | + Parameters |
| 16 | + ---------- |
| 17 | + nums : List[int] |
| 18 | + The input array of integers. |
| 19 | +
|
| 20 | + Returns |
| 21 | + ------- |
| 22 | + int |
| 23 | + The length of the longest arithmetic subsequence. |
| 24 | +
|
| 25 | + Examples |
| 26 | + -------- |
| 27 | + >>> longest_arithmetic_subsequence([3, 6, 9, 12]) |
| 28 | + 4 |
| 29 | + >>> longest_arithmetic_subsequence([9, 4, 7, 2, 10]) |
| 30 | + 3 |
| 31 | + >>> longest_arithmetic_subsequence([20, 1, 15, 3, 10, 5, 8]) |
| 32 | + 4 |
| 33 | + >>> longest_arithmetic_subsequence([]) # Empty array |
| 34 | + 0 |
| 35 | + >>> longest_arithmetic_subsequence(None) # Null array |
| 36 | + Traceback (most recent call last): |
| 37 | + ... |
| 38 | + ValueError: Input array cannot be None |
| 39 | + """ |
| 40 | + if nums is None: |
| 41 | + raise ValueError("Input array cannot be None") |
| 42 | + |
| 43 | + if len(nums) <= 1: |
| 44 | + return len(nums) |
| 45 | + |
| 46 | + dp = [{} for _ in range(len(nums))] |
| 47 | + max_length = 2 |
| 48 | + |
| 49 | + for i in range(len(nums)): |
| 50 | + for j in range(i): |
| 51 | + diff = nums[i] - nums[j] |
| 52 | + dp[i][diff] = dp[j].get(diff, 1) + 1 |
| 53 | + max_length = max(max_length, dp[i][diff]) |
| 54 | + |
| 55 | + return max_length |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + import doctest |
| 60 | + doctest.testmod() |
| 61 | + # sample test case |
| 62 | + nums = [3, 6, 9, 12] |
| 63 | + expected_length = 4 |
| 64 | + |
| 65 | + result = longest_arithmetic_subsequence(nums) |
| 66 | + print("Length of longest arithmetic subsequence:", result) |
0 commit comments