-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChocolateDistribution.java
More file actions
35 lines (29 loc) · 967 Bytes
/
ChocolateDistribution.java
File metadata and controls
35 lines (29 loc) · 967 Bytes
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
package Array;
import java.util.Arrays;
public class ChocolateDistribution {
/**
* Find the minimum difference of chocolates when it is distributed among m children.
*
* @param m - It is the number of children.
* @param n - It is the number of chocolate packets.
*/
static int findMinDiff(int[] arr, int n, int m) {
if (m == 0 || n == 0)
return 0;
Arrays.sort(arr);
if (n < m)
return -1;
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;
}
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;
int n = arr.length;
System.out.println("Minimum difference is " + findMinDiff(arr, n, m));
}
}