[LeetCode] Maximum Number of Groups Getting Fresh Donuts

1815. Maximum Number of Groups Getting Fresh Donuts

There is a donuts shop that bakes donuts in batches of batchSize. They have a rule where they must serve all of the donuts of a batch before serving any donuts of the next batch. You are given an integer batchSize and an integer array groups, where groups[i] denotes that there is a group of groups[i] customers that will visit the shop. Each customer will get exactly one donut.

When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group.

You can freely rearrange the ordering of the groups. Return the maximum possible number of happy groups after rearranging the groups.

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
class Solution {
int dp[241][31];
int backtracking(vector<int>& groups, int left, int sum, int batch) {
if(left == 0) return 0;
if(dp[sum][left] != -1) return dp[sum][left];
int &res = dp[sum][left] = 0;
for(int i = 1; i < groups.size(); i++) {
if(!groups[i]) continue;
groups[i]--;
res = max(res, backtracking(groups, left - 1, sum + i, batch));
groups[i]++;
}

res += (sum % batch == 0);
return res;
}
public:
int maxHappyGroups(int batchSize, vector<int>& groups) {
memset(dp,-1,sizeof(dp));
int happyDevides = 0;
vector<int> unbalanceGroups(batchSize);
for(int n : groups) {
int left = n % batchSize;
if(left == 0) happyDevides++;
else {
if(unbalanceGroups[batchSize - left]) {
unbalanceGroups[batchSize - left]--;
happyDevides++;
} else unbalanceGroups[left]++;
}
}
int left = accumulate(unbalanceGroups.begin(), unbalanceGroups.end(), 0);

return backtracking(unbalanceGroups,left,0,batchSize) + happyDevides;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/11/PS/LeetCode/maximum-number-of-groups-getting-fresh-donuts/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.