高盛 VO 面试真题解析:Partition Array Such That Maximum Difference Is K

16次阅读
没有评论

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:

Input: nums = [3,6,1,2,5], k = 2
Output: 2
Explanation: We can partition nums into the two subsequences [3,1,2] and [6,5]. The difference between the maximum and minimum value in the first subsequence is 3 - 1 = 2. The difference between the maximum and minimum value in the second subsequence is 6 - 5 = 1. Since two subsequences were created, we return 2. It can be shown that 2 is the minimum number of subsequences needed.

Example 2:

Input: nums = [1,2,3], k = 1
Output: 2
Explanation: We can partition nums into the two subsequences [1,2] and [3]. The difference between the maximum and minimum value in the first subsequence is 2 - 1 = 1. The difference between the maximum and minimum value in the second subsequence is 3 - 3 = 0. Since two subsequences were created, we return 2. Another optimal solution is to partition nums into [1] and [2,3].

Example 3:

Input: nums = [2,2,4,5], k = 0
Output: 3
Explanation: We can partition nums into the three subsequences [2,2], [4], and [5]. The difference between the maximum and minimum value in the first subsequence is 2 - 2 = 0. The difference between the maximum and minimum value in the second subsequence is 4 - 4 = 0. The difference between the maximum and minimum value in the third subsequence is 5 - 5 = 0. Since three subsequences were created, we return 3. It can be shown that 3 is the minimum number of subsequences needed.

Constraints:

1 <= nums.length <= 10^5

这道题的核心是把数组按数值范围分组:将 nums 排序后,尽量把相邻且最大值与最小值差不超过 k 的元素放在同一个子序列中;一旦当前组再加入一个数会超出 k,就必须新开一个子序列。这样问题就转化为在排序数组上做一次线性扫描,统计被分成了多少个连续区间,因此常见解法是先排序,再用贪心维护当前组的最小值和最大值,时间复杂度为 O(n log n),空间复杂度可做到 O(1) 或 O(n)(视排序实现而定)。

正文完
 0