Sponsored
Sponsored
Use these hints if you're stuck. Try solving on your own first.
Use dynamic programming.
Solve the problem in O(N^4) using a 3-states dp.
Let <code>dp[i][lastHeight][beforeLastHeight]</code> denote the maximum score if the grid was limited to column <code>i</code>, and the height of column <code>i - 1</code> is <code>lastHeight</code> and the height of column <code>i - 2</code> is <code>beforeLastHeight</code>.
The third state, <code>beforeLastHeight</code>, is used to determine which values of column <code>i - 1</code> will be added to the score. We can replace this state with another state that only takes two values 0 or 1.
Let <code>dp[i][lastHeight][isBigger]</code> denote the maximum score if the grid was limited to column <code>i</code>, and where the height of column <code>i - 1</code> is <code>lastHeight</code>. Additionally, if <code>isBigger == 1</code>, the number of black cells in column <code>i</code> is assumed to be larger than the number of black cells in column <code>i - 2</code>, and vice versa. Note that if our assumption is wrong, it would lead to a suboptimal score and, therefore, it would not be considered as the final answer.