Maximum sum possible from given Matrix by performing given operations
Last Updated :
23 Nov, 2021
Given a matrix arr[][] of dimensions 2 * N, the task is to maximize the sum possible by selecting at most one element from each column such that no two consecutive elements are chosen from the same row.
Examples:
Input: arr[][] = {{1, 50, 21, 5}, {2, 10, 10, 5}}
Output: 67
Explanation: Elements arr[1][0]( = 2), arr[0][1]( = 50), arr[0][2]( = 10) and arr[0][3]( = 5) can be chosen. Therefore, sum = 2 + 50 + 10 + 5 = 67.
Input: arr[][] = {{9, 5, 3, 7, 3}, {50, 8, 1, 50, 5}}
Output: 108
Explanation: Elements arr[1][0]( = 50), arr[0][1]( = 5), arr[1][3]( = 50) and arr[0][4]( = 3) can be chosen. Therefore, sum = 50 + 5 + 50 + 3 = 108.
Dynamic Programming Approach: The problem can be solved using dynamic programming. Follow the steps below to solve the problem:
- Initialize an array dp[][] to store the following transition states:
dp[0][i] = max(dp[1][i+1], dp[0][i+2]) + arr[0][i]
dp[1][i] = max(dp[0][i+1], dp[1][i+2]) + arr[1][i]
where, dp[j][i] stores the maximum possible sum to reach cell arr[j][i] starting from the last column where 0 <= i < N and 0 <= j < 2.
Base case:
dp[0][N-1] = arr[0][N-1]
dp[1][N-1] = arr[1][N-1]
- Traverse from (N - 2)th column to the 0th column and for each row, update dp[j][i] as dp[j][i] = max(dp[(j ^ 1)][i+1], dp[j][i+2]) + arr[j][i] where ^ represents Bitwise XOR.
- After completing the traversal, print max(dp[0][0], dp[1][0]) as the maximum possible sum.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <iostream>
#include <vector>
using namespace std;
// Function to print the maximum sum
void maxSum(vector<vector<int> > arr,
int n, int m)
{
// Dp table
vector<vector<int> > dp(n);
// Initializing dp array with 0s
for (int i = 0; i < 2; i++) {
dp[i] = vector<int>(m);
for (int j = 0; j < m; j++) {
dp[i][j] = 0;
}
}
// Base case
dp[0][m - 1] = arr[0][m - 1];
dp[1][m - 1] = arr[1][m - 1];
// Traverse each column
for (int j = m - 2; j >= 0; j--) {
// Update answer for both rows
for (int i = 0; i < 2; i++) {
if (i == 1) {
dp[i][j] = max(
arr[i][j] + dp[0][j + 1],
arr[i][j] + dp[0][j + 2]);
}
else {
dp[i][j] = max(
arr[i][j] + dp[1][j + 1],
arr[i][j] + dp[1][j + 2]);
}
}
}
// Print the maximum sum
cout << max(dp[0][0], dp[1][0]);
}
// Driver Code
int main()
{
// Given array
vector<vector<int> > arr
= { { 1, 50, 21, 5 },
{ 2, 10, 10, 5 } };
// Number of Columns
int N = arr[0].size();
// Function calls
maxSum(arr, 2, N);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG{
// Function to print the maximum sum
static void maxSum(int[][] arr, int n, int m)
{
// Dp table
int[][] dp = new int[n][m + 1];
// Initializing dp array with 0s
for(int i = 0; i < 2; i++)
{
for(int j = 0; j <= m; j++)
{
dp[i][j] = 0;
}
}
// Base case
dp[0][m - 1] = arr[0][m - 1];
dp[1][m - 1] = arr[1][m - 1];
// Traverse each column
for(int j = m - 2; j >= 0; j--)
{
// Update answer for both rows
for (int i = 0; i < 2; i++)
{
if (i == 1)
{
dp[i][j] = Math.max(
arr[i][j] + dp[0][j + 1],
arr[i][j] + dp[0][j + 2]);
}
else
{
dp[i][j] = Math.max(
arr[i][j] + dp[1][j + 1],
arr[i][j] + dp[1][j + 2]);
}
}
}
// Print the maximum sum
System.out.println(Math.max(dp[0][0],
dp[1][0]));
}
// Driver Code
public static void main(String[] args)
{
// Given array
int[][] arr = { { 1, 50, 21, 5 },
{ 2, 10, 10, 5 } };
// Number of Columns
int N = arr[0].length;
// Function calls
maxSum(arr, 2, N);
}
}
// This code is contributed by akhilsaini
Python3
# Python3 program for the above approach
# Function to print the maximum sum
def maxSum(arr, n, m):
# Dp table
dp = [[0 for i in range(m + 1)]
for i in range(2)]
# Initializing dp array with 0s
# for (i = 0 i < 2 i++) {
# dp[i] = vector<int>(m)
# for (j = 0 j < m j++) {
# dp[i][j] = 0
# }
# }
# Base case
dp[0][m - 1] = arr[0][m - 1]
dp[1][m - 1] = arr[1][m - 1]
# Traverse each column
for j in range(m - 2, -1, -1):
# Update answer for both rows
for i in range(2):
if (i == 1):
dp[i][j] = max(arr[i][j] + dp[0][j + 1],
arr[i][j] + dp[0][j + 2])
else:
dp[i][j] = max(arr[i][j] + dp[1][j + 1],
arr[i][j] + dp[1][j + 2])
# Print the maximum sum
print(max(dp[0][0], dp[1][0]))
# Driver Code
if __name__ == '__main__':
# Given array
arr = [ [ 1, 50, 21, 5 ],
[ 2, 10, 10, 5 ] ]
# Number of Columns
N = len(arr[0])
# Function calls
maxSum(arr, 2, N)
# This code is contributed by mohit kumar 29
C#
// C# program for the above approach
using System;
class GFG{
// Function to print the maximum sum
static void maxSum(int[, ] arr, int n, int m)
{
// Dp table
int[, ] dp = new int[n, m + 1];
// Initializing dp array with 0s
for(int i = 0; i < 2; i++)
{
for(int j = 0; j <= m; j++)
{
dp[i, j] = 0;
}
}
// Base case
dp[0, m - 1] = arr[0, m - 1];
dp[1, m - 1] = arr[1, m - 1];
// Traverse each column
for(int j = m - 2; j >= 0; j--)
{
// Update answer for both rows
for(int i = 0; i < 2; i++)
{
if (i == 1)
{
dp[i, j] = Math.Max(
arr[i, j] + dp[0, j + 1],
arr[i, j] + dp[0, j + 2]);
}
else
{
dp[i, j] = Math.Max(
arr[i, j] + dp[1, j + 1],
arr[i, j] + dp[1, j + 2]);
}
}
}
// Print the maximum sum
Console.WriteLine(Math.Max(dp[0, 0],
dp[1, 0]));
}
// Driver Code
public static void Main()
{
// Given array
int[, ] arr = { { 1, 50, 21, 5 },
{ 2, 10, 10, 5 } };
// Number of Columns
int N = arr.GetLength(1);
// Function calls
maxSum(arr, 2, N);
}
}
// This code is contributed by akhilsaini
JavaScript
<script>
// JavaScript program to implement
// the above approach
// Function to print the maximum sum
function maxSum(arr, n, m)
{
// Dp table
let dp = new Array(n);
// Loop to create 2D array using 1D array
for (var i = 0; i < dp.length; i++) {
dp[i] = new Array(2);
}
// Initializing dp array with 0s
for(let i = 0; i < 2; i++)
{
for(let j = 0; j <= m; j++)
{
dp[i][j] = 0;
}
}
// Base case
dp[0][m - 1] = arr[0][m - 1];
dp[1][m - 1] = arr[1][m - 1];
// Traverse each column
for(let j = m - 2; j >= 0; j--)
{
// Update answer for both rows
for (let i = 0; i < 2; i++)
{
if (i == 1)
{
dp[i][j] = Math.max(
arr[i][j] + dp[0][j + 1],
arr[i][j] + dp[0][j + 2]);
}
else
{
dp[i][j] = Math.max(
arr[i][j] + dp[1][j + 1],
arr[i][j] + dp[1][j + 2]);
}
}
}
// Print the maximum sum
document.write(Math.max(dp[0][0],
dp[1][0]));
}
// Driver Code
// Given array
let arr = [[ 1, 50, 21, 5 ],
[ 2, 10, 10, 5 ]];
// Number of Columns
let N = arr[0].length;
// Function calls
maxSum(arr, 2, N);
</script>
Time Complexity: O(N), where N is the number of columns.
Auxiliary Space: O(N)
Efficient Approach: Follow the steps below to optimize the above approach
- Initialize two variables r1 and r2 to store the maximum sum for 1st and 2nd rows respectively.
- Traverse over the length of the row, i.e. 0 to N - 1 and for each element arr[i], update r1 as r1 = max(r1, r2 + arr[0][i]) and r2 as r2 = max(r2, r1 + arr[1][i]).
- After traversing, print max(r1, r2) as the maximum sum.
Below is the implementation of the above approach:
C++
// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to print the maximum sum
// possible by selecting at most one
// element from each column such that
// no consecutive pairs are selected
// from a single row
void maxSum(vector<vector<int> > arr, int n)
{
// Initialize variables
int r1 = 0, r2 = 0;
// Traverse each column
for(int i = 0; i < n; i++)
{
// r1, r2 = max(r1, r2 + arr[0][i]),
// max(r2, r1 + arr[1][i])
int temp = r1;
r1 = max(r1, r2 + arr[0][i]);
r2 = max(r2, temp + arr[1][i]);
}
// Print answer
cout << max(r1, r2);
}
// Driver Code
int main()
{
vector<vector<int>> arr = { { 1, 50, 21, 5 },
{ 2, 10, 10, 5 } };
// Numberof columns
int n = arr[0].size();
maxSum(arr, n);
return 0;
}
// This code is contributed by akhilsaini
Java
// Java code for the above approach
import java.io.*;
import java.util.*;
class GFG{
// Function to print the maximum sum
// possible by selecting at most one
// element from each column such that
// no consecutive pairs are selected
// from a single row
static void maxSum(int[][] arr, int n)
{
// Initialize variables
int r1 = 0, r2 = 0;
// Traverse each column
for(int i = 0; i < n; i++)
{
int temp = r1;
r1 = Math.max(r1, r2 + arr[0][i]);
r2 = Math.max(r2, temp + arr[1][i]);
}
// Print answer
System.out.println(Math.max(r1, r2));
}
// Driver Code
public static void main(String args[])
{
int[][] arr = { { 1, 50, 21, 5 },
{ 2, 10, 10, 5 } };
// Numberof columns
int n = arr[0].length;
maxSum(arr, n);
}
}
// This code is contributed by akhilsaini
Python
# Python code for the above approach
# Function to print the maximum sum
# possible by selecting at most one
# element from each column such that
# no consecutive pairs are selected
# from a single row
def maxSum(arr, n):
# Initialize variables
r1 = r2 = 0
# Traverse each column
for i in range(n):
r1, r2 = max(r1, r2 + arr[0][i]), max(r2, r1 + arr[1][i])
# Print answer
print(max(r1, r2))
# Driver Code
arr = [[1, 50, 21, 5], [2, 10, 10, 5]]
# Numberof columns
n = len(arr[0])
maxSum(arr, n)
C#
// C# code for the above approach
using System;
class GFG{
// Function to print the maximum sum
// possible by selecting at most one
// element from each column such that
// no consecutive pairs are selected
// from a single row
static void maxSum(int[, ] arr, int n)
{
// Initialize variables
int r1 = 0, r2 = 0;
// Traverse each column
for(int i = 0; i < n; i++)
{
int temp = r1;
r1 = Math.Max(r1, r2 + arr[0, i]);
r2 = Math.Max(r2, temp + arr[1, i]);
}
// Print answer
Console.WriteLine(Math.Max(r1, r2));
}
// Driver Code
public static void Main()
{
int[, ] arr = { { 1, 50, 21, 5 },
{ 2, 10, 10, 5 } };
// Numberof columns
int n = arr.GetLength(1);
maxSum(arr, n);
}
}
// This code is contributed by akhilsaini
JavaScript
<script>
// Javascript code for the above approach
// Function to print the maximum sum
// possible by selecting at most one
// element from each column such that
// no consecutive pairs are selected
// from a single row
function maxSum(arr , n) {
// Initialize variables
var r1 = 0, r2 = 0;
// Traverse each column
for (i = 0; i < n; i++) {
var temp = r1;
r1 = Math.max(r1, r2 + arr[0][i]);
r2 = Math.max(r2, temp + arr[1][i]);
}
// Print answer
document.write(Math.max(r1, r2));
}
// Driver Code
var arr = [ [ 1, 50, 21, 5 ],
[ 2, 10, 10, 5 ] ];
// Numberof columns
var n = arr[0].length;
maxSum(arr, n);
// This code is contributed by todaysgaurav
</script>
Time Complexity: O(N), where N is the number of columns.
Auxiliary Space: O(1)
Similar Reads
Maximum possible Array sum after performing given operations
Given array arr[] of positive integers, an integer Q, and arrays X[] and Y[] of size Q. For each element in arrays X[] and Y[], we can perform the below operations: For each query from array X[] and Y[], select at most X[i] elements from array arr[] and replace all the selected elements with integer
9 min read
Maximum possible array sum after performing the given operation
Given an array arr[] of size N, the task is to find the maximum sum of the elements of the array after applying the given operation any number of times. In a single operation, choose an index 1 ? i < N and multiply both arr[i] and arr[i - 1] by -1.Examples: Input: arr[] = {-10, 5, -4} Output: 19
9 min read
Maximum Possible Product in Array after performing given Operations
Given an array with size N. You are allowed to perform two types of operations on the given array as described below: Choose some position i and j, such that (i is not equals to j), replace the value of a[j] with a[i]*a[j] and remove the number from the ith cell.Choose some position i and remove the
13 min read
Maximum score possible after performing given operations on an Array
Given an array A of size N, the task is to find the maximum score possible of this array. The score of an array is calculated by performing the following operations on the array N times: If the operation is odd-numbered, the score is incremented by the sum of all elements of the current array. If th
15+ min read
Maximum strength in a Matrix after performing specified operations
Given a matrix of N * M containing {0, 1, #}. The task is to find the maximum value of strength based on following rules: Initial strength is zero.If you encounter a 0, Strength decreases by 2.If you encounter a 1, Strength increases by 5.If you encounter a #, Jumps to the start of a new row without
7 min read
Find the Maximum sum of the Array by performing the given operations
Given an Array A[] of size N with repeated elements and all array elements are positive, the task is to find the maximum sum by applying the given operations: Select any 2 indexes and select 2 integers(say x and y) such that the product of the elements(x and y) is equal to the product of the element
5 min read
Maximum value obtained by performing given operations in an Array
Given an array arr[], the task is to find out the maximum obtainable value. The user is allowed to add or multiply the two consecutive elements. However, there has to be at least one addition operation between two multiplication operations (i.e), two consecutive multiplication operations are not all
10 min read
Maximize first array element by performing given operations at most K times
Given an array arr[] of size N an integer K, the task is to find the maximize the first element of the array by performing the following operations at most K times: Choose a pair of indices i and j (0 ? i, j ? N-1) such that |i ? j| = 1 and arri > 0.Set arri = arri ? 1 and arrj = arrj + 1 on thos
7 min read
Maximize the minimum value of Array by performing given operations at most K times
Given array A[] of size N and integer K, the task for this problem is to maximize the minimum value of the array by performing given operations at most K times. In one operation choose any index and increase that array element by 1. Examples: Input: A[] = {3, 1, 2, 4, 6, 2, 5}, K = 8Output: 4Explana
10 min read
Maximum non-negative product of a path from top left to bottom right of given Matrix
Given an integer matrix mat[][] of dimensions N * M, the task is to print the maximum product of matrix elements in the path from the top-left cell (0, 0) to the bottom-right cell (N â 1, M â 1) of the given matrix. Only possible moves from any cell (i, j) is (i + 1, j) or (i, j + 1). If the maximum
10 min read