Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Maximize Grid Happiness

Updated
5 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1659" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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: Introverts start with 120 happiness and lose 30 happiness for each neighbor (introvert or extrovert). Extroverts start with 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 <= 5 0 <= introvertsCount, extrovertsCount <= min(m * n, 6)

Explanation

  • Dynamic Programming with Bitmasking: Represent the state of the grid using a bitmask to denote the arrangement of introverts and extroverts in the last row. This allows efficient calculation of happiness based on neighboring cells. Use DP to explore all possible arrangements and track maximum happiness.
    • State Representation: Define a DP state as dp[row][mask][introverts][extroverts], where row is the current row being filled, mask represents the configuration of the previous row, and introverts and extroverts are the remaining counts.
    • Transitions: Iterate through all possible configurations for the current row. Calculate the happiness gained by placing introverts and extroverts in the current row, considering neighbors in the current and previous rows. Update the DP table with the maximum happiness obtained so far.
  • Runtime Complexity: O(m * n * 3n * introvertsCount * extrovertsCount), where 3n reflects the state space of the mask.
  • Storage Complexity: O(m * 3n * introvertsCount * extrovertsCount).

Code

    def getMaxGridHappiness(m: int, n: int, introvertsCount: int, extrovertsCount: int) -> int:
    dp = {}

    def calculate_happiness(mask, new_mask, introverts, extroverts):
        happiness = 0
        for i in range(n):
            person = (new_mask >> (2 * i)) & 3
            if person == 1:  # Introvert
                happiness += 120
                if i > 0:
                    neighbor = (new_mask >> (2 * (i - 1))) & 3
                    if neighbor != 0:
                        happiness -= 30
                if i < n - 1:
                    neighbor = (new_mask >> (2 * (i + 1))) & 3
                    if neighbor != 0:
                        happiness -= 30
                neighbor = (mask >> (2 * i)) & 3
                if neighbor != 0:
                    happiness -= 30

            elif person == 2:  # Extrovert
                happiness += 40
                if i > 0:
                    neighbor = (new_mask >> (2 * (i - 1))) & 3
                    if neighbor != 0:
                        happiness += 20
                if i < n - 1:
                    neighbor = (new_mask >> (2 * (i + 1))) & 3
                    if neighbor != 0:
                        happiness += 20
                neighbor = (mask >> (2 * i)) & 3
                if neighbor != 0:
                    happiness += 20

        return happiness

    def solve(row, mask, introverts, extroverts):
        if row == m:
            return 0

        if (row, mask, introverts, extroverts) in dp:
            return dp[(row, mask, introverts, extroverts)]

        max_happiness = 0
        for new_mask in range(3 ** n):
            temp_introverts = introverts
            temp_extroverts = extroverts
            valid = True
            curr_happiness = 0

            temp_mask = new_mask
            people = []

            for _ in range(n):
              val = temp_mask % 3
              people.append(val)
              temp_mask //= 3

            for val in people:
              if val == 1:
                temp_introverts -= 1
              elif val == 2:
                temp_extroverts -= 1

            if temp_introverts < 0 or temp_extroverts < 0:
                valid = False

            if valid:
                curr_happiness = calculate_happiness(mask, new_mask, introverts, extroverts)
                next_mask = 0
                for i in range(n):
                    person = (new_mask >> (2 * i)) & 3
                    next_mask |= (person << (2 * i))

                max_happiness = max(max_happiness, curr_happiness + solve(row + 1, next_mask, temp_introverts, temp_extroverts))

        dp[(row, mask, introverts, extroverts)] = max_happiness
        return max_happiness

    return solve(0, 0, introvertsCount, extrovertsCount)

More from this blog

C

Chatmagic blog

2894 posts