-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChocolateDistributionProblem
More file actions
74 lines (70 loc) · 1.75 KB
/
ChocolateDistributionProblem
File metadata and controls
74 lines (70 loc) · 1.75 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package Udemyprograms;
public class Arrays10GeeksForGeeks {
public static int ChocolateDistribution(int[] arr, int m) {
/*
* sort the given array.
* initialise a min value = 0;
* run a loop
* inside a loop compare the i and i+5th element
* if the diff is the minimum diff return the diff
*/
if (m == 0 || arr.length == 0) {
return 0;
}
sort(arr, 0, arr.length - 1);
int min = Integer.MAX_VALUE;
int i = 0;
while ((i + m - 1) <= arr.length - 1) {
if (arr[i + m - 1] - arr[i] < min) {
min = arr[i + m - 1] - arr[i];
}
i++;
}
return min;
}
public static void sort(int[] arr, int L, int R) {
if (L < R) {
int mid = (L + R) / 2;
sort(arr, L, mid);
sort(arr, mid + 1, R);
merge(arr, L, mid, R);
}
}
public static void merge(int[] arr, int L, int mid, int R) {
int l = mid - L + 1;
int r = R - mid;
int[] leftArray = new int[l];
int[] rightArray = new int[r];
for (int i = 0; i < l; ++i) {
leftArray[i] = arr[L + i];
}
for (int j = 0; j < r; ++j) {
rightArray[j] = arr[mid + 1 + j];
}
int i = 0;
int j = 0;
int k = L;
while (i < l && j < r) {
if (leftArray[i] <= rightArray[j]) {
arr[k++] = leftArray[i++];
} else {
arr[k++] = rightArray[j++];
}
}
while (i < l) {
arr[k++] = leftArray[i++];
}
while (j < r) {
arr[k++] = rightArray[j++];
}
}
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};
System.out.println(ChocolateDistribution(arr, 7));
// for (int i = 0; i < arr.length; i++) {
// System.out.println(arr[i]);
// }
}
}