Maximize Grid Happiness - Problem

Imagine you're a city planner tasked with arranging residents in an m x n residential grid to maximize overall community happiness! 🏘️

You have two personality types to work with:

  • Introverts: Start with 120 happiness but lose 30 points for each neighbor
  • Extroverts: Start with 40 happiness but gain 20 points for each neighbor

Given introvertsCount introverts and extrovertsCount extroverts, you need to strategically place them (or leave some out) to achieve the maximum possible grid happiness.

Neighbors are those living in directly adjacent cells (north, south, east, west). The total happiness is the sum of all residents' individual happiness scores.

Input & Output

example_1.py — Basic Grid
$ Input: m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2
Output: 240
💡 Note: Place 1 introvert and 2 extroverts optimally. Extroverts gain happiness from neighbors while introvert should be isolated.
example_2.py — Small Grid
$ Input: m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1
Output: 260
💡 Note: In a 3×1 grid, place extrovert in middle (gains from 2 neighbors) and introverts on ends (each loses from 1 neighbor).
example_3.py — Edge Case
$ Input: m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0
Output: 240
💡 Note: With only introverts available, place them to minimize neighbor interactions (diagonal arrangement gives 60×4 = 240).

Constraints

  • 1 ≤ m, n ≤ 5
  • 0 ≤ introvertsCount ≤ min(6, m × n)
  • 0 ≤ extrovertsCount ≤ min(6, m × n)
  • Grid size is small enough for DP with bitmask approach

Visualization

Tap to expand
Maximize Grid Happiness INPUT 2 x 3 Grid (m=2, n=3) I Introvert x1 Base: 120, -30/neighbor E Extrovert x2 Base: 40, +20/neighbor m = 2, n = 3 introvertsCount = 1 extrovertsCount = 2 ALGORITHM STEPS 1 State Definition Track row, remaining I/E, and prev row config 2 Try Placements For each cell: Empty, Introvert, or Extrovert 3 Calculate Delta Add base happiness, adjust for neighbors 4 Maximize via DP Use memoization to find optimal config Optimal Placement: I E E I isolated, E's are neighbors FINAL RESULT I E E Happiness Breakdown: Introvert: 120 (no neighbors) Extrovert 1: 40 + 20 = 60 Extrovert 2: 40 + 20 = 60 Total: 120 + 60 + 60 = 240 Maximum Happiness 240 Key Insight: Introverts should be isolated (no neighbors) to keep their 120 happiness intact. Extroverts benefit from being adjacent to each other (+20 each). Use bitmask DP with state compression on previous row configuration for O(m * 3^n * 3^n * introverts * extroverts) time. TutorialsPoint - Maximize Grid Happiness | Optimal Solution
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
27.6K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen