oneby7

Range Queries Segment tree

611. Longest Increasing Subsequence II

Hard

You are given an array of integers nums and an integer k. Return the length of the longest subsequence of nums that is strictly increasing and in which each element is at most k bigger than the one before it.

A subsequence keeps some of the elements, in their original order, and drops the rest. The kept elements do not have to be next to each other in nums. So every step from one kept element to the next goes up by at least 1 and by at most k.

Example 1

Input: nums = [3, 9, 4, 6, 15, 7, 10, 20], k = 3

Output: 5

Explanation: The subsequence 3, 4, 6, 7, 10 goes up by 1, 2, 1 and 3, so every step is at most 3. The 20 cannot come after the 10, because that step is 10.

Example 2

Input: nums = [5, 5, 6, 6, 7], k = 1

Output: 3

Explanation: The longest one is 5, 6, 7. The two 5s cannot both be kept, because the subsequence must be strictly increasing.

Example 3

Input: nums = [4, 10, 16, 1000000000], k = 6

Output: 3

Explanation: The steps from 4 to 10 and from 10 to 16 are exactly 6, which is allowed. The last value is far too big to come after 16.

Check your understanding

Work out the answer for this input before you write any code.

nums = [1, 4, 7, 9, 9, 10], k = 2

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • 1 ≤ k ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.