Problem Description
Given an integer array nums and an integer k, partition nums into one or more subsequences so that every element appears in exactly one subsequence and the difference between the maximum and minimum value in each subsequence is at most k. Return the minimum number of subsequences required.
Key Insights
- Sorting the array helps group numbers that are close in value.
- A greedy strategy can be applied by iterating through the sorted array and starting a new subsequence whenever the difference from the start of the current subsequence exceeds k.
- Since subsequences preserve the original order, sorting does not break the requirement because we are free to pick any elements as long as order is kept, and the sorted order is a valid order.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting, with an additional O(n) for the linear scan. Space Complexity: O(n) due to the auxiliary space for sorting.
Solution
The approach involves two main steps. First, sort the input array. Then, iterate over the sorted array while maintaining the starting element of the current subsequence. If the difference between the current element and the starting element exceeds k, then the current subsequence cannot include this element; hence, increment the count of subsequences and start a new subsequence from the current element. This greedy grouping ensures that each subsequence has a maximum difference that does not exceed k while minimizing the total number of subsequences.