forked from IDeserve/learn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDistributeChocolates
51 lines (44 loc) · 1.6 KB
/
DistributeChocolates
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.ideserve.saurabh.questions;
import java.util.Arrays;
/**
* <b>IDeserve <br>
* <a href="https://www.youtube.com/c/IDeserve">https://www.youtube.com/c/IDeserve</a>
* <br><br>
* Distribute Chocolates</b><br>
* @author Saurabh
*
*/
public class DistributeChocolates {
public static void main(String[] args) {
int[] chocolatePackets = {12, 4, 7, 9, 2, 23, 25, 41 , 30, 40, 28, 42, 30, 44, 48, 43, 50};
distributeChocolates(chocolatePackets, 7);
}
public static void distributeChocolates(int[] chocolatePackets, int n) {
// If there are no chocolates or number of students is 0
if(chocolatePackets == null || chocolatePackets.length == 0 || n == 0) {
return;
}
// Sort the chocolatePackets
Arrays.sort(chocolatePackets);
int m = chocolatePackets.length;
if(m < n) {
System.out.println("Number of students is more than number of packets. Cannot distribute!");
return;
}
int minDiff = chocolatePackets[m-1]; // Largest number of chocolates
int first = 0;
int last = 0;
int diff = 0;
for(int i = 0; i + n - 1 < m; i++) {
diff = chocolatePackets[i+n-1] - chocolatePackets[i];
if(diff < minDiff) {
minDiff = diff;
first = i;
last = i+n-1;
}
}
System.out.println("Chocolate packet distribution to " + n + " students is: ");
for(int i = first; i <= last; i++)
System.out.print(chocolatePackets[i] + " ");
}
}