Wednesday 4 January 2017

Chocolate Distribution Problem

There are M chocolate packets each packet can have variable number of chocolates in each packet. There are N students (N < M). Distribute chocolate packets to student such that

a) Each student should get 1 packet
b) The difference between the number of chocolates in packet with maximum chocolates and packet with minimum chocolates given to the students should be minimum.

M = 1, 3, 4, 6, 5 (5 packets with specified number of chocolates in them)
N = 3
Output = 3, 5.

import java.util.Arrays;

public class Chocalate {

     /**
      * @param chocalates
      * @param std
      * @return min difference
      */
     private static int getChocaltes(int[] chocalates, int std) {
           Arrays.sort(chocalates);
          
           int min = Integer.MAX_VALUE;
          
           for(int i=0;i<chocalates.length-std+1;i++) {
                min = Math.min(chocalates[i+std-1]-chocalates[i], min);
           }
           return min;
     }
    
     public static void main(String[] args) {

           int[] chocalates = {1, 3, 4, 6, 5};
           int students = 3;
          
           int minDiff = getChocaltes(chocalates, students);
           System.out.println("Minimum difference is # "+ minDiff);
     }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...