-
Notifications
You must be signed in to change notification settings - Fork 3
/
Problem-2.java
75 lines (50 loc) · 1.86 KB
/
Problem-2.java
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
75
/**
* @author AkashGoyal
* @date 02/06/2021
*/
/**
--------------------- Problem----------->> Chocolate Distribution Problem
Problem Link :- https://practice.geeksforgeeks.org/problems/chocolate-distribution-problem3825/1
Reference:- https://www.youtube.com/watch?v=T_2CATt_XyQ
*/
/*
----------------------------------------------------------------------------------
Ex:- 7 3 2 4 9 12 56 --> M=3
2 3 4 7 9 12 56 --> sort
now make a window of size m--> 3
(loop)-->>
[2 3 4] 7 9 12 56
| |
i m+i-1 --> 2--> min_sum--> compare
2 [3 4 7] 9 12 56
| |
i m+i-1 --> 4>2 --> don't
2 3 [4 7 9] 12 56
| |
i m+i-1 --> 5>2 --> don't
2 3 4 [7 9 12] 56
| |
i m+i-1 --> 5>2 --> don't
2 3 4 7 [9 12 56]
| |
-----> Return 2(ans)--> so we are getting the minimum (from window)
----------------------------------------------------------------------------------
*/
public long findMinDiff (ArrayList<Long> a, long n, long m)
{
// your code here
Collections.sort(a);
long min_diff=Integer.MAX_VALUE;
int k=(int)m-1; //m+i-1
int i=0;
while(k<n)
{
if(min_diff>a.get(k)-a.get(i))
{
min_diff=a.get(k)-a.get(i);
}
k++;
i++;
}
return min_diff;
}