Partition Array Such That Maximum Difference Is K

You are given an integer array nums and an integer k. You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences.

Return the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at most k.

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

Example 1
Inputnums = [3,6,1,2,5], k = 2
Output2
We can partition nums into [3,1,2] and [6,5], whose maximum-minimum differences are 2 and 1, so 2 is the minimum number of subsequences needed.
Example 2
Inputnums = [1,2,3], k = 1
Output2
We can partition nums into [1,2] and [3], whose maximum-minimum differences are 1 and 0, so 2 subsequences are needed.

Constraints

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

Asked at 2 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