#1659

Maximize Grid Happiness

Hard
Dynamic ProgrammingBit ManipulationMemoizationBitmaskDynamic ProgrammingBitmasking
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(3^(m*n))
O(m * n * 3^(n))
Space
O(1)
O(m * introvertsCount * extrovertsCount * 2^n)
💡

Intuition

Time O(m * n * 3^(n))Space O(m * introvertsCount * extrovertsCount * 2^n)

The optimal solution uses dynamic programming with bitmasking to efficiently explore configurations of the grid. It keeps track of the maximum happiness by considering the state of each row and the remaining introverts and extroverts.

⚙️

Algorithm

3 steps
  1. 1Step 1: Define a DP function that takes the current row, remaining introverts, remaining extroverts, and the previous row's configuration.
  2. 2Step 2: For each cell in the current row, decide whether to place an introvert, an extrovert, or leave it empty.
  3. 3Step 3: Calculate the happiness based on the current configuration and recursively call the DP function for the next row.
solution.py19 lines
1def maxGridHappiness(m, n, introvertsCount, extrovertsCount):
2    dp = {}  # memoization
3    def dfs(row, introverts_left, extroverts_left, prev_mask):
4        if row == m:
5            return 0
6        if (row, introverts_left, extroverts_left, prev_mask) in dp:
7            return dp[(row, introverts_left, extroverts_left, prev_mask)]
8        max_happiness = 0
9        for mask in range(1 << n):
10            happiness = calculate_happiness(mask, prev_mask, introverts_left, extroverts_left)
11            if happiness != -1:
12                max_happiness = max(max_happiness, happiness + dfs(row + 1, introverts_left, extroverts_left, mask))
13        dp[(row, introverts_left, extroverts_left, prev_mask)] = max_happiness
14        return max_happiness
15
16    return dfs(0, introvertsCount, extrovertsCount, 0)
17
18# Helper function to calculate happiness based on mask
19...

Complexity note: The complexity is reduced by using bitmasking to represent the state of each row, allowing us to efficiently calculate happiness without generating all configurations.

  • 1Understanding the happiness calculation is crucial for optimizing placements.
  • 2Dynamic programming can significantly reduce the number of configurations we need to evaluate.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.