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)
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 firstname.lastname@example.org. 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.
- Maximum difference of zeros and ones in binary string | Set 2 (O(n) time)
- Maximum path sum in matrix
- Count the number of ways to tile the floor of size n x m using 1 x m size tiles
- Ways to sum to N using array elements with repetition allowed
- Find distinct elements common to all rows of a matrix
- Find a peak element in a 2D array
- Maximum path sum for each position with jumps under divisibility condition
- Maximum subsequence sum such that no three are consecutive
- Maximum weight path ending at any element of last row in a matrix
- Count distinct occurrences as a subsequence
- Count number of ways to cover a distance
- Word Break Problem | DP-32
- 0-1 Knapsack Problem | DP-10
- Edit Distance | DP-5
- Maximum sum such that no two elements are adjacent