Longest Increasing Subsequence II

You are given an integer array nums and an integer k.

Find the longest subsequence of nums that meets the following requirements:

  • The subsequence is strictly increasing.
  • The difference between adjacent elements in the subsequence is at most k.

Return the length of the longest subsequence that meets the requirements.

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 1
Inputnums = [4,2,1,4,3,4,5,8,15], k = 3
Output5
The longest subsequence that meets the requirements is [1, 3, 4, 5, 8], which has length 5; [1, 3, 4, 5, 8, 15] is invalid because 15 - 8 = 7 is larger than 3.
Example 2
Inputnums = [7,4,5,1,8,12,4,7], k = 5
Output4
The longest subsequence that meets the requirements is [4, 5, 8, 12], which has length 4.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i], k <= 10^5

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate