Skip to content

Latest commit

 

History

History
36 lines (27 loc) · 979 Bytes

114.md

File metadata and controls

36 lines (27 loc) · 979 Bytes

Chocolate Distribution Problem

LeetCode Link

long long findMinDiff(vector<long long> a, long long n, long long m){
    //code
    if (m == 0 || n == 0) {
        return 0;
    }
    
    // Sort the array to arrange packets in increasing order of chocolates
    sort(a.begin(), a.end());
    
    // If there are fewer packets than students, return -1 as we cannot distribute
    if (n < m) {
        return -1;
    }
    
    // Initialize the minimum difference as a large number
    long long minDiff = LLONG_MAX;
    
    // Iterate over all possible windows of size M
    for (long long i = 0; i + m - 1 < n; i++) {
        // Calculate the difference between the maximum and minimum chocolates in the current window
        long long diff = a[i + m - 1] - a[i];
        
        // Update the minimum difference if the current difference is smaller
        if (diff < minDiff) {
            minDiff = diff;
        }
    }
    
    return minDiff;
    
}