VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-sum-2-x-n-grid-no-two-elements-adjacent/

⇱ Max Sum in a 2 * n Grid with No Two Adjacent - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Max Sum in a 2 * n Grid with No Two Adjacent

Last Updated : 13 Jun, 2026

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.

[Naive Approach] Using Recursion - O(2 ^ n) Time O(n) Space

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 column i + 1. Recursively explore both choices and return the maximum sum obtained.


Output
7

Time Complexity: O(2 ^ n)
Auxiliary Space: O(n)

[Expected Approach] Using Dynamic Programming - O(n) Time O(1) Space

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]]

  • Initialize the states using the first column as: prev_top = 1, prev_bot = 2 and prev_none = 0.
  • For column 1, the states become: curr_top = 4, curr_bot = 0 and curr_none = 2.
  • For column 2, the states become: curr_top = 7, curr_bot = 2 and curr_none = 4.

The final answer is max(7, 2, 4) = 7.


Output
7

Time Complexity: O(n)
Auxiliary Space: O(1)

Comment