[LeetCode] 2294. 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. Note that another optimal solution is to partition nums into the two subsequences [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 subsequences is 2 - 2 = 0.
The difference between the maximum and minimum value in the second subsequences is 4 - 4 = 0.
The difference between the maximum and minimum value in the third subsequences 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 <= 105
0 <= nums[i] <= 105
0 <= k <= 105

划分数组使最大差为 K。

给你一个整数数组 nums 和一个整数 k 。你可以将 nums 划分成一个或多个 子序列 ,使 nums 中的每个元素都 恰好 出现在一个子序列中。

在满足每个子序列中最大值和最小值之间的差值最多为 k 的前提下,返回需要划分的 最少 子序列数目。

子序列 本质是一个序列,可以通过删除另一个序列中的某些元素(或者不删除)但不改变剩下元素的顺序得到。

思路

思路是贪心。题目要求我们把 input 数组划分成多个子序列,而且注意例子,我们发现子序列是无序的。所以这里我们可以选择排序。排序过后,对于每个合法的子序列,我们是哦先可以得到子序列中最小的元素 min,然后遍历后面的数字,如果当前数字 num - min > k,则说明当前数字 num 不能和 min 在同一个子序列中,所以我们需要新开一个子序列。否则就可以和 min 在同一个子序列中。

复杂度

时间O(nlogn)
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int partitionArray(int[] nums, int k) {
Arrays.sort(nums);
int n = nums.length;
int min = nums[0];
int count = 1;
for (int i = 0; i < n; i++) {
int num = nums[i];
if (num - min > k) {
count++;
min = num;
}
}
return count;
}
}

[LeetCode] 2294. Partition Array Such That Maximum Difference Is K
https://shurui91.github.io/posts/3847178217.html
Author
Aaron Liu
Posted on
June 18, 2025
Licensed under