#2294
Medium Algorithms Partition array such that maximum difference is k
Array Greedy Sorting
81.8% acceptance
Feb 25, 2026
1175
47
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.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn partition_array(mut nums: Vec<i32>, k: i32) -> i32 {
nums.sort_unstable();
let mut count = 1;
let mut start = nums[0];
for &num in &nums[1..] {
if num - start > k {
count += 1;
start = num;
}
}
count
}
}