Split an array into the fewest groups so that within each group, the difference between the maximum and minimum element is at most .
Problem
You are given an integer array nums and an integer k.
Partition the array into several non-empty groups such that every element belongs to exactly one group, and for each group the difference between the largest and smallest value in that group is at most k.
Return the minimum possible number of groups.
A group does not need to contain consecutive elements from the original array; this is a partition by values, not by index order.
Intuition
To minimize the number of groups, try to place as many numbers together as possible while keeping the value spread within k.
Input Format
nums: an integer arrayk: a non-negative integer
Output Format
Return a single integer: the minimum number of groups needed.
Constraints
1 <= nums.length0 <= k- Elements are integers
If exact original platform constraints are unknown, use the standard interpretation: all values fit in 32-bit signed integers.
Example 1
Input
nums = [3, 6, 1, 2, 5], k = 2
Output
2
Explanation
One optimal partition is [1, 2, 3] and [5, 6]. In each group, max - min is at most 2.
Example 2
Input
nums = [1, 2, 3], k = 0
Output
3
Explanation
No two different values can be in the same group when k = 0, so each element must be its own group.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.