[LeetCode] Maximize Grid Happiness

1659. Maximize Grid Happiness

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
int dp[25][7][7][64][64];
int N, M;
int getCost(int y, int x, int im, int em, int additional) {
int res = 0;
if(x and im & 1) res += additional - 30;
if(x and em & 1) res += additional + 20;
if(y and im & (1<<(M-1))) res += additional - 30;
if(y and em & (1<<(M-1))) res += additional + 20;
return res;
}

int dfs(int p, int ic, int ec, int im, int em) {
int y = p / M, x = p % M;
if(y == N) return 0;

int& res = dp[p][ic][ec][im][em];
if(res != -1) return res;

int nim = (im<<1) & 63, nem = (em<<1) & 63;
res = dfs(p + 1, ic, ec, nim, nem);
if(ic) {
int c = 120 + getCost(y,x,im, em, -30);
res = max(res, c + dfs(p + 1, ic - 1, ec, nim + 1, nem));
}
if(ec) {
int c = 40 + getCost(y,x,im, em, 20);
res = max(res, c + dfs(p + 1, ic, ec - 1, nim, nem + 1));
}
return res;
}
public:
int getMaxGridHappiness(int n, int m, int introvertsCount, int extrovertsCount) {
memset(dp,-1,sizeof(dp));
N = n, M = m;

return dfs(0,introvertsCount, extrovertsCount, 0, 0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/02/PS/LeetCode/maximize-grid-happiness/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.