Partition Array Such That Maximum Difference Is K

medium array greedy sorting

Problem

You are given an integer array nums and an integer k. Split every element into groups so that, within any group, the difference between the largest and smallest value is at most k. Return the minimum number of groups you need. Each element must belong to exactly one group, and the order of elements does not matter.

Inputnums = [3, 6, 1, 2, 5], k = 2
Output2
Sort → [1, 2, 3, 5, 6]. Group {1, 2, 3} (max−min = 2) and group {5, 6} (max−min = 1). Two groups suffice.

def partition_array(nums, k):
    nums.sort()
    groups = 0
    start = None
    for x in nums:
        if start is None or x - start > k:
            groups += 1
            start = x
    return groups
function partitionArray(nums, k) {
  nums.sort((a, b) => a - b);
  let groups = 0;
  let start = null;
  for (const x of nums) {
    if (start === null || x - start > k) {
      groups += 1;
      start = x;
    }
  }
  return groups;
}
class Solution {
    public int partitionArray(int[] nums, int k) {
        Arrays.sort(nums);
        int groups = 0;
        int start = Integer.MIN_VALUE;
        for (int x : nums) {
            if (groups == 0 || x - start > k) {
                groups += 1;
                start = x;
            }
        }
        return groups;
    }
}
int partitionArray(vector<int>& nums, int k) {
    sort(nums.begin(), nums.end());
    int groups = 0;
    int start = 0;
    for (int x : nums) {
        if (groups == 0 || x - start > k) {
            groups += 1;
            start = x;
        }
    }
    return groups;
}
Time: O(n log n) Space: O(1)