forked from tanus786/CP-Codes-HackOctober-Fest-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Chocolate distribution problem GFG
107 lines (48 loc) · 1.24 KB
/
Chocolate distribution problem GFG
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
//{ Driver Code Starts
//Initial Template for Java
import java.io.*;
import java.util.*;
class GfG
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0)
{
int n = sc.nextInt();
ArrayList<Integer> arr = new ArrayList<>();
for(int i = 0;i<n;i++)
{
int x = sc.nextInt();
arr.add(x);
}
int m = sc.nextInt();
Solution ob = new Solution();
System.out.println(ob.findMinDiff(arr,n,m)); }
}
}
// } Driver Code Ends
//User function Template for Java
class Solution
{
public long findMinDiff (ArrayList<Integer> a, int n, int m)
{
if(m==0 || n==0){
return 0;
}
if(n<m){
return -1;
}
Collections.sort(a);
int min = a.get(a.size()-1);
int minUpto;
for(int i = 0;i + m - 1 < n;i++){
minUpto=a.get(i+m-1)-a.get(i);
if(minUpto<min){
min=minUpto;
}
}
return min;
}
}