Skip to content

Commit a92ce9c

Browse files
committed
Add solution for Issue #2605: Fresh Donuts
1 parent bce4c37 commit a92ce9c

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
from functools import lru_cache
2+
3+
def maxHappyGroups(batchSize, groups):
4+
# Time Complexity: O(k^m) where k is batchSize and m is number of groups
5+
# Space Complexity: O(batchSize)
6+
7+
# 1. Simplify groups by taking modulo
8+
remainder_counts = [0] * batchSize
9+
happy_groups = 0
10+
11+
for g in groups:
12+
rem = g % batchSize
13+
if rem == 0:
14+
happy_groups += 1
15+
else:
16+
remainder_counts[rem] += 1
17+
18+
# 2. Match complements (e.g., remainder 1 and batchSize-1)
19+
for i in range(1, batchSize // 2 + 1):
20+
if i == batchSize - i:
21+
happy_groups += remainder_counts[i] // 2
22+
remainder_counts[i] %= 2
23+
else:
24+
pairs = min(remainder_counts[i], remainder_counts[batchSize - i])
25+
happy_groups += pairs
26+
remainder_counts[i] -= pairs
27+
remainder_counts[batchSize - i] -= pairs
28+
29+
# 3. DFS to optimize remaining groups
30+
@lru_cache(None)
31+
def dfs(current_rem, counts):
32+
max_val = 0
33+
total_remaining = sum(counts)
34+
35+
if total_remaining == 0:
36+
return 0
37+
38+
for i in range(1, batchSize):
39+
if counts[i] > 0:
40+
new_counts = list(counts)
41+
new_counts[i] -= 1
42+
43+
is_happy = 1 if current_rem == 0 else 0
44+
res = is_happy + dfs((current_rem + i) % batchSize, tuple(new_counts))
45+
max_val = max(max_val, res)
46+
47+
return max_val
48+
49+
happy_groups += dfs(0, tuple(remainder_counts))
50+
return happy_groups
51+
52+
# Driver Code
53+
if __name__ == "__main__":
54+
print(f"Test 1: {maxHappyGroups(3, [1,2,3,4,5,6])}") # Expected: 4
55+
print(f"Test 2: {maxHappyGroups(4, [1,3,2,5,2,2,1,6])}") # Expected: 4

0 commit comments

Comments
 (0)