742. Longest Even-Step Subsequence
A weather station records one temperature per hour in the array nums. An analyst wants to pick some of the readings, keeping their original time order but allowed to skip hours in between, so that the picked readings rise or fall by the same fixed amount from each pick to the next. The amount may be positive, negative or zero.
Return the largest number of readings that can be picked this way. A single reading, or any two readings, always qualify, so the answer is at least 1 (and at least 2 when there are two or more readings).
Aim for time O(n^2) and space O(n^2) in the worst case, where n is the length of nums.
Example 1
- Input:
- nums = [3,11,7,19,15,23,31]
- Output:
- 4
- Explanation:
Picking 7, 15, 23, 31 (step 8) skips the readings 3, 11, 19 in between and gives 4.
Example 2
- Input:
- nums = [5,5,5,2,5]
- Output:
- 4
- Explanation:
Skipping the 2 leaves four 5s with step 0, so the answer is 4.
Example 3
- Input:
- nums = [1,100,60,20,-20]
- Output:
- 4
- Explanation:
The last four readings fall by 40 each time, so the answer is 4.
Constraints
1 ≤ nums.length ≤ 2000
-104 ≤ nums[i] ≤ 104
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n^2)
- Space
- O(n^2)