Chocolate Distribution Problem in Java

Chocolate Distribution Problem in Java

Here, on this page, we will discuss the Chocolate Distribution Problem in Java Programming Language. We are given an array of n integers these value represents the number of chocolates in a packet. Each packet can have a variable number of chocolates. There are m students, the task is to distribute chocolate packets such that: 

  • Every student gets one packet.
  • The difference between the number of chocolates in the packet with maximum chocolates and the packet with minimum chocolates given to the students is minimum.
Chocolate Distribution Problem in Java

Algorithm :

  • First sort the array, using inbuilt sort() function.
  • Take a variable say mini = INT_MAX, so that it can store the required value.
  • Now, iterate over the entire array, and for every i-th element, find the difference between the a[i+m-1] and a[i], if it is minimum than mini value than set, mini to that difference.
  • After the complete iteration print the mini value.
Chocolate Distribution Problem in Java
Run
import java.util.*;
public
class Main {
    static int findMinDiff(int arr[], int n, int m) {
        // if there are no chocolates or
        // number of students is 0

        if (m == 0 || n == 0) return 0;
        // Sort the given packets
        Arrays.sort(arr);

        // Number of students cannot be
        // more than number of packets
        if (n < m) return -1;

        // Largest number of chocolates
        int min_diff = Integer.MAX_VALUE;

        for (int i = 0; i + m – 1 < n; i++) {
            int diff = arr[i + m – 1] – arr[i];
            if (diff < min_diff) min_diff = diff;
        }

        return min_diff;
    }
    /* Driver program to test above function */
    public
    static void main(String[] args) {
        int arr[] = {12, 4, 7, 9, 2, 23, 25, 41, 30, 40, 28, 42, 30, 44, 48, 43, 50};
        int m = 7;  // Number of students

        int n = arr.length;
        System.out.println(“Minimum difference is ” + findMinDiff(arr, n, m));
    }
}