![]() |
VOOZH | about |
Given a grid mat of dimension 2 * n, the task is to find out the maximum sum such that no two chosen numbers are adjacent, vertically, diagonally or horizontally.
Examples:
Input: mat = [[1, 4, 5], [2, 0, 0]]
Output: 7
Explanation: Choose 2 from the first column and 5 from the third column. Their sum is 7.
Input: mat = [[1, 2], [3, 4]]
Output: 4
Explanation: Choose 4 from the second column. The maximum obtainable sum is 4.
Table of Content
The idea is to process the matrix column by column. For each column, either pick the maximum value from the current column and move to column
i + 2, or skip the current column and move to columni + 1. Recursively explore both choices and return the maximum sum obtained.
7
Time Complexity: O(2 ^ n)
Auxiliary Space: O(n)
The idea is to process the matrix column by column while maintaining three states representing whether the top cell, bottom cell, or no cell was selected in the previous column. Update these states for each column and keep only the previous column values to achieve constant extra space.
Let us understand with example:
Input: mat = [[1, 4, 5], [2, 0, 0]]
The final answer is max(7, 2, 4) = 7.
7
Time Complexity: O(n)
Auxiliary Space: O(1)