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. There are introvertsCount introverts and extrovertsCount extroverts.
You should decide how many people you want to live in the grid and assign each of them one grid cell. Note that you do not have to have all the people living in the grid.
The happiness of each person is calculated as follows:
120 happiness and lose 30 happiness for each neighbor (introvert or extrovert).40 happiness and gain 20 happiness for each neighbor (introvert or extrovert).Neighbors live in the directly adjacent cells north, east, south, and west of a person's cell.
The grid happiness is the sum of each person's happiness. Return the maximum possible grid happiness.
Example 1:
Input: m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2 Output: 240 Explanation: Assume the grid is 1-indexed with coordinates (row, column). We can put the introvert in cell (1,1) and put the extroverts in cells (1,3) and (2,3). - Introvert at (1,1) happiness: 120 (starting happiness) - (0 * 30) (0 neighbors) = 120 - Extrovert at (1,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60 - Extrovert at (2,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60 The grid happiness is 120 + 60 + 60 = 240. The above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells.
Example 2:
Input: m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1 Output: 260 Explanation: Place the two introverts in (1,1) and (3,1) and the extrovert at (2,1). - Introvert at (1,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90 - Extrovert at (2,1) happiness: 40 (starting happiness) + (2 * 20) (2 neighbors) = 80 - Introvert at (3,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90 The grid happiness is 90 + 80 + 90 = 260.
Example 3:
Input: m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0 Output: 240
Constraints:
1 <= m, n <= 50 <= introvertsCount, extrovertsCount <= min(m * n, 6)Problem Overview: You are given an m x n grid and a limited number of introverts and extroverts. Each person contributes a base happiness value, but neighboring cells change that value depending on the combination of people placed. The goal is to place people in the grid so the total happiness score is maximized.
Approach 1: Backtracking with Pruning (Exponential Time, O(3^(m*n)) time, O(m*n) space)
This approach explores every possible way to fill the grid: leave the cell empty, place an introvert, or place an extrovert. During recursion you track remaining introverts/extroverts and compute the incremental happiness contribution from the top and left neighbors. Pruning helps reduce work by stopping branches where remaining cells cannot beat the current best score. While conceptually straightforward, the branching factor of three per cell leads to exponential complexity, so it only works because the grid size is small. This method is useful for understanding the scoring mechanics before introducing dynamic programming.
Approach 2: Dynamic Programming with State Representation (O(m * 3^n * 3^n * introverts * extroverts) time, O(3^n * introverts * extroverts) space)
The optimal solution compresses each row configuration into a base‑3 state where each cell is 0 = empty, 1 = introvert, or 2 = extrovert. Since n ≤ 5, there are at most 3^5 = 243 possible row states. Precompute three things for every state: how many introverts/extroverts it uses, the internal row happiness, and the interaction score with another row above it. Then run DP row by row where the state is dp[row][prevState][introvertsLeft][extrovertsLeft]. For each row you iterate over all valid current states and combine them with the previous row state. This captures both horizontal and vertical neighbor effects while dramatically reducing the search space. The state compression technique is a classic combination of bitmask/state encoding and memoization to reuse overlapping subproblems.
Recommended for interviews: The dynamic programming state‑compression approach is what interviewers expect. Backtracking shows you understand the constraints and happiness rules, but it scales poorly. The DP solution demonstrates stronger problem‑solving skills: recognizing small grid width, encoding row states efficiently, and reusing results with memoization.
The problem can be tackled using Dynamic Programming (DP) by representing each cell's state in the grid. You evaluate placing introverts, extroverts, or leaving a cell empty, tracking the happiness and transitions.
Define a DP array dp[cells][in][ex] where cells is the linearized grid index, in is the count of introverts placed, and ex is the count of extroverts placed. Compute maximum happiness for placing persons in a cell conditioned on its previous state.
The solution uses a recursive function with memoization to track happiness states in a grid traversed in a linearized fashion. Each cell considers the option of being empty, occupied by an introvert, or occupied by an extrovert. The recursive state space branches according to available introverts and extroverts, computing transitions based on current grid neighbors using bitmask representation for fast neighbors computation.
Time complexity: O(m * n * 3^(m*n) * introvertsCount * extrovertsCount). Space complexity: O(m * n * 3^(m*n) * introvertsCount * extrovertsCount) due to memoization storage being used to store intermediate states.
The problem can alternatively be approached using backtracking with pruning. This technique evaluates possible placements of introverts and extroverts in the grid, backtracking when a placement results in a sub-optimal state.
This solution uses a backtracking approach to explore all possible ways to place people in the grid. The function recursively checks each cell and tries placing an introvert, extrovert, or leaving it empty. It prunes non-promising branches based on remaining counts of introverts and extroverts.
Time Complexity: O(3^(m*n)) due to the exhaustive traversal through the potential grid arrangements. Space Complexity: O(m * n) for the grid representation.
We notice that in the problem, 1 leq m, n leq 5, and each grid cell has three states: no personnel assigned, introverted personnel assigned, and extroverted personnel assigned. Therefore, we can use 0, 1, 2 to represent these three states, and each row in the grid can be represented by a ternary number of length n.
We define a function dfs(i, pre, ic, ec), which represents the maximum happiness of the grid starting from the i-th row, with the state of the previous row being pre, ic introverted people left, and ec extroverted people left. The answer is dfs(0, 0, introvertsCount, extrovertsCount).
The calculation process of the function dfs(i, pre, ic, ec) is as follows:
If i = m, it means that all rows have been processed, so return 0;
If ic = 0 and ec = 0, it means that all people have been assigned, so return 0;
Otherwise, enumerate the current row's state cur, where cur \in [0, 3^n), then calculate the happiness f[cur] of the current row, and the contribution g[pre][cur] to the happiness between the state pre of the previous row, and recursively calculate dfs(i + 1, cur, ic - ix[cur], ec - ex[cur]), finally return the maximum value of f[cur] + g[pre][cur] + dfs(i + 1, cur, ic - ix[cur], ec - ex[cur]), that is:
$
dfs(i, pre, ic, ec) = max_{cur} {f[cur] + g[pre][cur] + dfs(i + 1, cur, ic - ix[cur], ec - ex[cur])}
Where:
represents the number of introverted people in state cur; represents the number of extroverted people in state cur; represents the initial happiness of the people in state cur; represents the contribution to happiness of two adjacent state rows.These values can be obtained through preprocessing. And we can use the method of memoization to avoid repeated calculations.
The time complexity is O(3^{2n} times (m times ic times ec + n)), and the space complexity is O(3^{2n} + 3^n times m times ic times ec). Where ic and ec$ represent the number of introverted and extroverted people, respectively.
Python
Java
C++
Go
TypeScript
We can consider searching each grid cell, each time searching a position (i, j), we denote pos = i times n + j. Then its left and upper adjacent grids will affect their happiness contribution.
We define a function dfs(pos, pre, ic, ec), which represents the maximum happiness of the grid when we search to position pos, and the state of the previous n grid cells is pre, with ic introverted people left, and ec extroverted people left. The answer is dfs(0, 0, introvertsCount, extrovertsCount).
The calculation process of the function dfs(pos, pre, ic, ec) is as follows:
If pos = m times n, it means that all grid cells have been processed, so return 0;
If ic = 0 and ec = 0, it means that all people have been assigned, so return 0;
Otherwise, we calculate the state up = \frac{pre}{3^{n-1}} of the upper adjacent grid cell of the current grid cell based on pre, and the state left = pre bmod 3 of the left adjacent grid cell (note that if pos is in the 0-th column, then left = 0).
Next, we enumerate the state i of the current grid cell, where i \in [0, 3). Then the state of the current n grid cells is cur = pre bmod 3^{n-1} times 3 + i, and the happiness contribution of the current grid cell and its left and upper adjacent grid cells is h[up][i]+h[left][i]; the happiness of the current grid cell itself depends on whether personnel are assigned to this position, and whether the assigned personnel are introverted or extroverted. If they are introverted, the happiness is 120, if they are extroverted, the happiness is 40, otherwise, the happiness is 0; then, if personnel are assigned to the current grid cell, we need to update ic or ec when we recursively call the function. Accumulate these happiness values, and take the maximum value as the return value of the function.
Similar to Solution 1, we can also use the method of memoization to avoid repeated calculations.
The time complexity is O(3^{n+1} times m times n times ic times ec), and the space complexity is O(3^n times m times n times ic times ec). Where ic and ec represent the number of introverted and extroverted people, respectively.
Python
Java
C++
Go
TypeScript
| Approach | Complexity |
|---|---|
| Dynamic Programming with State Representation | Time complexity: O(m * n * 3^(m*n) * introvertsCount * extrovertsCount). Space complexity: O(m * n * 3^(m*n) * introvertsCount * extrovertsCount) due to memoization storage being used to store intermediate states. |
| Backtracking with Pruning | Time Complexity: O(3^(m*n)) due to the exhaustive traversal through the potential grid arrangements. Space Complexity: O(m * n) for the grid representation. |
| Ternary State Compression + Memoization | — |
| Contour Line Memorized Search | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Backtracking with Pruning | O(3^(m*n)) | O(m*n) | Good for understanding the scoring rules and brute-force reasoning on very small grids. |
| Dynamic Programming with Row State Compression | O(m * 3^n * 3^n * I * E) | O(3^n * I * E) | Optimal approach when grid width is small (n ≤ 5). Efficiently handles neighbor interactions using precomputed row states. |
花花酱 LeetCode 1659. Maximize Grid Happiness - 刷题找工作 EP371 • Hua Hua • 2,614 views views
Watch 5 more video solutions →Practice Maximize Grid Happiness with our built-in code editor and test cases.
Practice on FleetCode