Given a rectangular grid of dimension 2 x n. We need to find out the maximum sum such that no two chosen numbers are adjacent, vertically, diagonally or horizontally.
Input : 1 4 5 2 0 0 Output : 7 If we start from 1 then we can add only 5 or 0. So max_sum = 6 in this case. If we select 2 then also we can add only 5 or 0. So max_sum = 7 in this case. If we select from 4 or 0 then there is no further elements can be added. So, Max sum is 7. Input : 1 2 3 4 5 6 7 8 9 10 Output : 24
This problem is an extension of Maximum sum such that no two elements are adjacent. Only thing to be changed is to take maximum element of both row of a particular column. We traverse column by column and maintain maximum sum considering two cases.
1) An element of current column is included. In this case we take maximum of two elements in current column.
2) An element of current column is excluded (or not included)
Below is the implementation of above steps.
Time Complexity: O(n)
Space Complexity: O(2n) which is equal to O(n)
This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Minimum product in a grid of adjacent elements
- Sum of the count of number of adjacent squares in an M X N grid
- Check if a grid can become row-wise and column-wise sorted after adjacent swaps
- Collect maximum points in a grid using two traversals
- Find maximum sum from top to bottom row with no adjacent diagonal elements
- Construct a Matrix with no element exceeding X and sum of two adjacent elements not exceeding Y
- Number of ways to paint K cells in 3 x N grid such that no P continuous columns are left unpainted
- Color a grid such that all same color cells are connected either horizontally or vertically
- Maximum product of 4 adjacent elements in matrix
- Maximum perimeter of a square in a 2D grid
- Minimum difference between adjacent elements of array which contain elements from each row of a matrix
- Check if all the elements can be made of same parity by inverting adjacent elements
- Shortest distance between two cells in a matrix or grid
- Minimum number of Water to Land conversion to make two islands connected in a Grid
- Minimum sum falling path in a NxN grid
- Maximum difference of sum of elements in two rows in a matrix
- Count of all subsequences having adjacent elements with different parity
- Search a Word in a 2D Grid of characters
- Unique paths in a Grid with Obstacles
- Largest connected component on a grid