Chocolate Distribution problem

Pattern: Sliding window: fixed size

medium

After sorting, the best m packets always sit next to each other. Slide a window of m over the sorted array and take the smallest last-minus-first.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Each packet holds some number of chocolates. You give one packet to each of m students. Choose the packets so that the difference between the largest and the smallest packet handed out is as small as possible, and return that difference. For example, [7, 3, 2, 4, 9, 12, 56] with m = 3 gives 2 (packets 2, 3 and 4), and [3, 4, 1, 9, 56, 7, 9, 12] with m = 5 gives 6 (packets 3, 4, 7, 9 and 9).

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name findMinDiff is this guide's own. You may assume 1 ≤ m ≤ n, and the function may sort the array.

Think first

  • Only the largest and smallest chosen packets matter. Once you fix the smallest, which other packets should you pick?
  • After sorting, could the best choice ever skip a packet and then pick a bigger one?
  • How many groups of m neighbours does a sorted array of n values have?

Hints

    Brute force, and why it fails

    Try every group of m packets: that is "n choose m" groups, which is huge even for 30 packets. This guide uses that search only to check its tests on small arrays.

    The key insight

    Sorting puts close values next to each other, and a best group is always a block of m neighbours. Then each window's spread is one subtraction.

    Dry run

    20 
    31 
    42 
    73 
    94 
    125 
    566 
    m3

    packets = [7, 3, 2, 4, 9, 12, 56] and m = 3 students. Sort first, giving [2, 3, 4, 7, 9, 12, 56].

    Step 1 of 4

    The plan

    sort a
    best = infinity
    for i from 0 to n - m:
        best = min(best, a[i + m - 1] - a[i])
    return best
    

    Complexity

    Time
    O(n log n)
    Space
    O(1)

    Sorting dominates. The window pass is O(n), and only best is stored (apart from what the sort itself uses).

    Edge cases

    • m = 1: any single packet, so the answer is 0.
    • m = n: every packet is used, so the answer is the largest minus the smallest.
    • Equal packets, as in [1, 1, 1, 1] with m = 2: 0.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int findMinDiff(int[] a, int m) {
            Arrays.sort(a);                         // the best m packets are next to each other once sorted
            int best = Integer.MAX_VALUE;
            for (int i = 0; i + m - 1 < a.length; i++) {
                best = Math.min(best, a[i + m - 1] - a[i]);   // window a[i..i+m-1]: biggest minus smallest
            }
            return best;
        }
    }

    C++

    class Solution {
    public:
        int findMinDiff(vector<int>& a, int m) {
            sort(a.begin(), a.end());               // the best m packets are next to each other once sorted
            int best = INT_MAX;
            for (int i = 0; i + m - 1 < static_cast<int>(a.size()); i++) {
                best = min(best, a[i + m - 1] - a[i]);   // window a[i..i+m-1]: biggest minus smallest
            }
            return best;
        }
    };

    Python

    class Solution:
        def findMinDiff(self, a: list[int], m: int) -> int:
            a.sort()                                # the best m packets are next to each other once sorted
            return min(a[i + m - 1] - a[i] for i in range(len(a) - m + 1))

    Common mistakes

    • Forgetting to sort, so the windows are not groups of close values.
    • Using a window of m + 1 or m - 1 by getting the end index wrong. The window from i ends at i + m - 1.
    • Looping i past n - m, which reads past the end of the array.

    Similar problems