Skip to problem
←

Chocolate Distribution

Easy 0 attempts

Given packet sizes in an array arr and m students, choose m distinct packets and give one packet to each student. Minimize the difference between the largest and smallest chosen packet sizes, and return that difference.

You may choose any packets; they do not need to be adjacent in the original array.

Function contract

Implement findMinDiff(arr, m), where arr lists packet sizes and m is the number of students. Choose m distinct packets, one per student.

Output: The minimum possible difference between the largest and smallest chosen packet sizes.

Example 1

Input
arr = [3,4,1,9,56,7,9,12]
m = 5
Output
6

Explanation: Choose packets with 3, 4, 7, 9, and 9 chocolates. Their difference is 9 - 3 = 6.

Example 2

Input
arr = [1,10,20]
m = 1
Output
0
Constraints
  • 1 <= arr.length <= 10^5
  • 1 <= arr[i] <= 10^9
  • 1 <= m <= arr.length

Sort the array. Then slide a window of size m across the sorted array and find the window where the difference between the last and first element is minimized.

javascript
function findMinDiff(arr, m) {
  if (m === 0 || arr.length === 0) return 0;
  arr.sort((a, b) => a - b);

  let minDiff = Infinity;
  for (let i = 0; i + m - 1 < arr.length; i++) {
    const diff = arr[i + m - 1] - arr[i];
    minDiff = Math.min(minDiff, diff);
  }

  return minDiff;
}

Time: O(n log n) for sorting Space: O(1) (ignoring sort space)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript