#1815
Maximum Number of Groups Getting Fresh Donuts
HardArrayDynamic ProgrammingBit ManipulationMemoizationBitmaskDynamic ProgrammingBit ManipulationGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution utilizes dynamic programming and bit manipulation to efficiently calculate the maximum number of happy groups by tracking the remainders when groups are served. This avoids the need to check every permutation.
⚙️
Algorithm
3 steps- 1Step 1: Create a frequency array to count how many groups have sizes that give the same remainder when divided by batchSize.
- 2Step 2: Use dynamic programming to explore combinations of these groups while keeping track of the current remainder.
- 3Step 3: Maximize the number of happy groups by ensuring that the sum of group sizes in each partition is 0 mod batchSize.
solution.py12 lines
1def maxHappyGroups(batchSize, groups):
2 from collections import Counter
3 freq = Counter(g % batchSize for g in groups)
4 dp = [-1] * batchSize
5 dp[0] = 0
6 for r in range(batchSize):
7 if freq[r] > 0:
8 for j in range(batchSize):
9 if dp[j] != -1:
10 new_rem = (j + r) % batchSize
11 dp[new_rem] = max(dp[new_rem], dp[j] + freq[r])
12 return dp[0] + (1 if freq[0] > 0 else 0)ℹ
Complexity note: The time complexity is O(n) since we iterate through the groups to create the frequency array and then through the batchSize for dynamic programming. The space complexity is O(n) due to the frequency and dp arrays.
- 1Understanding how to partition groups based on their sizes and the batch size is crucial.
- 2Using dynamic programming can significantly reduce the complexity of the problem.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.