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
120happiness but lose30points for each neighbor - Extroverts: Start with
40happiness but gain20points 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).
Visualization
Tap to expand
Understanding the Visualization
1
Understanding the Problem
Introverts lose happiness from neighbors (-30 each), extroverts gain happiness (+20 each). Goal: maximize total happiness.
2
Brute Force Insight
Trying all 3^(mรn) combinations is too slow - we need to identify overlapping subproblems.
3
Key Observation
Happiness only depends on direct neighbors. We can solve row by row, remembering previous row state.
4
DP State Design
State: (current_row, previous_row_configuration, introverts_left, extroverts_left)
5
Optimal Solution
Generate all 3^n row states, use DP with memoization to build solution incrementally.
Key Takeaway
๐ฏ Key Insight: By processing the grid row by row and using memoization to cache subproblem results, we transform an intractable exponential problem into an efficient dynamic programming solution that leverages the local nature of neighbor interactions.
Time & Space Complexity
Time Complexity
O(m ร 3^(2n) ร introvertsCount ร extrovertsCount)
For each of m rows, we have 3^n current states ร 3^n previous states, and we track counts of remaining people
โ Linear Growth
Space Complexity
O(3^(2n) ร introvertsCount ร extrovertsCount)
Memoization table stores results for all state combinations
โก Linearithmic Space
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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code