Skip to content

Commit 8790e3a

Browse files
authored
Create 1815-maximum-number-of-groups-getting-fresh-donuts.js
1 parent 6d9fb49 commit 8790e3a

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* @param {number} batchSize
3+
* @param {number[]} groups
4+
* @return {number}
5+
*/
6+
const maxHappyGroups = function (batchSize, groups) {
7+
const arr = new Array(batchSize + 1).fill(0)
8+
let result = 0
9+
// reduce group to groups of size group%n
10+
for (let gSize of groups) {
11+
arr[gSize % batchSize]++
12+
}
13+
14+
// Only need 1 step
15+
result += arr[0]
16+
arr[0] = 0
17+
18+
// Only need 2 step
19+
for (let i = 1; i < batchSize / 2; i++) {
20+
let min = Math.min(arr[i], arr[batchSize - i])
21+
arr[i] -= min
22+
arr[batchSize - i] -= min
23+
result += min
24+
}
25+
result += dfs(arr, 0, new Map())
26+
return result
27+
}
28+
29+
function dfs(arr, remain, cache) {
30+
let n = arr.length - 1
31+
const key = arr.join(',')
32+
if (cache.has(key)) return cache.get(key)
33+
let result = 0
34+
// greedy and short cut when we can finish the current round
35+
if (remain > 0 && arr[n - remain] > 0) {
36+
arr[n - remain]--
37+
result = dfs(arr, 0, cache)
38+
arr[n - remain]++
39+
} else {
40+
for (let i = 1; i < arr.length; i++) {
41+
if (arr[i] > 0) {
42+
arr[i]--
43+
result = Math.max(
44+
result,
45+
dfs(arr, (remain + i) % n, cache) + (remain == 0 ? 1 : 0)
46+
)
47+
arr[i]++
48+
}
49+
}
50+
}
51+
cache.set(key, result)
52+
return result
53+
}

0 commit comments

Comments
 (0)