Skip to content

Commit d865b08

Browse files
authored
Create main.cpp
1 parent 1590930 commit d865b08

File tree

1 file changed

+33
-0
lines changed
  • 25 - Greedy Algorithm Problems/06 - Chocolate Distribution Problem

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
public:
3+
// Function to find the minimum difference between the maximum and minimum values of m selected elements
4+
int findMinDiff(vector<int>& a, int m) {
5+
6+
// Step 1: Sort the array to bring the closest values together
7+
sort(a.begin(), a.end());
8+
9+
// Step 2: Initialize two pointers, i and j, to represent the window of m elements
10+
int i = 0;
11+
int j = m - 1;
12+
13+
// Step 3: Initialize the variable 'mini' to store the minimum difference found
14+
int mini = INT_MAX;
15+
16+
// Step 4: Iterate through the array using the sliding window approach
17+
// The window size is m elements
18+
while (j < a.size()) {
19+
// Calculate the difference between the maximum and minimum values in the current window (a[j] and a[i])
20+
int diff = a[j] - a[i];
21+
22+
// Step 5: Update 'mini' with the smaller value between the current minimum difference and the calculated difference
23+
mini = min(mini, diff);
24+
25+
// Move the window: increment both i and j to check the next possible set of m elements
26+
i++;
27+
j++;
28+
}
29+
30+
// Step 6: Return the minimum difference found
31+
return mini;
32+
}
33+
};

0 commit comments

Comments
 (0)