HardNo. 1659
Maximize Grid Happiness — LeetCode 1659 Python Solution
- Pattern
- Bit Manipulation
- Topics
- Bit Manipulation, Memoization, Dynamic Programming, Bitmask
- Reading time
- 8 min
- Source
- leetcode.com
The problem
You are given four integers, m, n, introvertsCount, and extrovertsCount. You have an m x n grid, and there are two types of people: introverts and extroverts.
Example
- Input
- m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2
- Output
- 240
- Explanation
- Assume the grid is 1-indexed with coordinates (row, column).
Python solution
class Solution:
def getMaxGridHappiness(
self, m: int, n: int, introvertsCount: int, extrovertsCount: int
) -> int:
@cache
def dfs(i: int, pre: int, ic: int, ec: int) -> int:
if i == m or (ic == 0 and ec == 0):
return 0
ans = 0
for cur in range(mx):
if ix[cur] <= ic and ex[cur] <= ec:
a = f[cur] + g[pre][cur]
b = dfs(i + 1, cur, ic - ix[cur], ec - ex[cur])
ans = max(ans, a + b)
return ans
mx = pow(3, n)
f = [0] * mx
g = [[0] * mx for _ in range(mx)]
h = [[0, 0, 0], [0, -60, -10], [0, -10, 40]]
bits = [[0] * n for _ in range(mx)]
ix = [0] * mx
ex = [0] * mx
for i in range(mx):
mask = i
for j in range(n):
mask, x = divmod(mask, 3)
bits[i][j] = x
if x == 1:
ix[i] += 1
f[i] += 120
elif x == 2:
ex[i] += 1
f[i] += 40
if j:
f[i] += h[x][bits[i][j - 1]]
for i in range(mx):
for j in range(mx):
for k in range(n):
g[i][j] += h[bits[i][k]][bits[j][k]]
return dfs(0, 0, introvertsCount, extrovertsCount)Complexity
- Time
- O(32n × (m × ic × ec + n))
- Space · auxiliary
- O(32n + 3n × m × ic × ec)
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1659. Maximize Grid Happiness is filed here because LeetCode tags it Bit Manipulation and Bitmask, which is the vocabulary this hub collects.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0464 | Can I Win | Medium |
| 0638 | Shopping Offers | Medium |
| 0698 | Partition to K Equal Sum Subsets | Medium |
| 1815 | Maximum Number of Groups Getting Fresh Donuts | Hard |
| 1655 | Distribute Repeating Integers | Hard |
| 0397 | Integer Replacement | Medium |
Frequently asked questions
- How hard is LeetCode 1659. Maximize Grid Happiness?
LeetCode 1659. Maximize Grid Happiness is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1659. Maximize Grid Happiness?
The Python solution on this page runs in O(32n × (m × ic × ec + n)).
- What is the space complexity of LeetCode 1659. Maximize Grid Happiness?
The Python solution on this page uses O(32n + 3n × m × ic × ec) auxiliary space.
- What topics does LeetCode 1659. Maximize Grid Happiness cover?
LeetCode 1659. Maximize Grid Happiness is tagged Bit Manipulation, Memoization, Dynamic Programming and Bitmask on LeetCode.