Maximize matrix as per given condition - GeeksforGeeks

21 May, 2021
You are given a N*N matrix, where each element of matrix lies in the range 0 to M. You can apply the below operation on matrix any number of times:  
Choose any two consecutive elements
Increment one of them by 1 and decrease other by 1
Note: The elements should remain within the range 0 to M after applying above operations. The task is to find the maximum value of the expression shown below that can be obtained after performing the above operation on matrix if required:  
res += (i+j)*A[i][j]

for 0 <= i, j <= N
Examples:  
Input : A[][] = {1, 2,
                 5, 1}
        M = 5
Output : RESULT = 27
Matrix : 0 0
         4 5

Input : A[][] = {3, 4,
                 5, 4}
        M = 6
Output : RESULT = 43
Matrix : 0 4
         6 6
 
Algorithm : Below is the step by step algorithm to do this:  
First of all, calculate the sum of all elements of given matrix as SUM.Start from last element that i.e. A(n, n) and move backward towards A(0,0) anti-diagonally as A(n, n), A(n, n-1), A(n-1, n), A(n, n-2), A(n-1, n-1), A(n-2, n).....Fill up each cell of matrix with M and update SUM = SUM- M for each element till SUM < M. Now, Fill the SUM value at next place in order if it is greater than zero and all other remaining place as zero.Finally you can calculate RESULT as per above mentioned formula.
First of all, calculate the sum of all elements of given matrix as SUM.
Start from last element that i.e. A(n, n) and move backward towards A(0,0) anti-diagonally as A(n, n), A(n, n-1), A(n-1, n), A(n, n-2), A(n-1, n-1), A(n-2, n).....
Fill up each cell of matrix with M and update SUM = SUM- M for each element till SUM < M. Now, Fill the SUM value at next place in order if it is greater than zero and all other remaining place as zero.
Finally you can calculate RESULT as per above mentioned formula.
Example : Input Matrix:  
Solution Matrix after applying above algorithm :  
Below is the implementation of above idea :  
C++
Java
Python3
C#
PHP
Javascript
// CPP to maximize matrix result#include<bits/stdc++.h>using namespace std;#define n 4 // utility function for maximize matrix resultint maxMatrix(int A[][n], int M){    int sum = 0, res = 0;    for ( int i=0; i<n ; i++)        for ( int j=0; j<n; j++)            sum += A[i][j];     // diagonals below longest diagonal    // starting from last element of matrix    for (int j=n-1; j>0; j--)    {        for (int i=0; i<n-j; i++)        {            if (sum > M)            {                A[n-1-i][j+i] = M;                sum -= M;            }            else            {                A[n-1-i][j+i] = sum;                sum -= sum;            }        }    }      // diagonals above longest diagonal    for (int i=n-1; i>=0; i--)    {        for (int j=0; j<=i; j++)         {            if (sum > M)            {                A[i-j][j] = M;                sum -= M;            }            else            {                A[i-j][j] = sum;                sum -= sum;            }        }    }     // calculating result    for (int i=0; i<n; i++)    {         for (int j=0; j<n;j++)             res += (i+j+2) * A[i][j];    }    return res;} // driver program int main(){    int A[n][n] = { 1, 2, 3, 4,                    5, 6, 7, 8,                    9, 1, 1, 2,                    3, 4, 5, 6};    int m = 9;    cout << maxMatrix(A, m);    return 0;}
// Java to maximize matrix result class GFG {     static final int n = 4; // utility function for maximize matrix result    static int maxMatrix(int A[][], int M) {        int sum = 0, res = 0;        for (int i = 0; i < n; i++) {            for (int j = 0; j < n; j++) {                sum += A[i][j];            }        }         // diagonals below longest diagonal        // starting from last element of matrix        for (int j = n - 1; j > 0; j--) {            for (int i = 0; i < n - j; i++) {                if (sum > M) {                    A[n - 1 - i][j + i] = M;                    sum -= M;                } else {                    A[n - 1 - i][j + i] = sum;                    sum -= sum;                }            }        }         // diagonals above longest diagonal        for (int i = n - 1; i >= 0; i--) {            for (int j = 0; j <= i; j++) {                if (sum > M) {                    A[i - j][j] = M;                    sum -= M;                } else {                    A[i - j][j] = sum;                    sum -= sum;                }            }        }         // calculating result        for (int i = 0; i < n; i++) {            for (int j = 0; j < n; j++) {                res += (i + j + 2) * A[i][j];            }        }        return res;    } // driver program    static public void main(String[] args) {        int A[][] = {{1, 2, 3, 4},        {5, 6, 7, 8},        {9, 1, 1, 2},        {3, 4, 5, 6}};        int m = 9;        System.out.println(maxMatrix(A, m));    }} // This code is contributed by Rajput-Ji
# Python to maximize matrix resultn = 4 # utility function for maximize# matrix resultdef maxMatrix(A, M):    sum, res = 0, 0    for i in range(n):        for j in range(n):            sum += A[i][j]     # diagonals below longest diagonal    # starting from last element of matrix    for j in range(n - 1, 0, -1):        for i in range(n - j):            if (sum > M):                A[n - 1 - i][j + i] = M                sum -= M            else:                A[n - 1 - i][j + i] = sum                sum -= sum                     # diagonals above longest diagonal    for i in range(n - 1, -1, -1):        for j in range(i + 1):            if (sum > M):                A[i - j][j] = M                sum -= M            else:                A[i - j][j] = sum                sum -= sum                     # calculating result    for i in range(n):        for j in range(n):            res += (i + j + 2) * A[i][j]    return res # Driver Codeif __name__ == '__main__':    A = [[1, 2, 3, 4],         [5, 6, 7, 8],         [9, 1, 1, 2],         [3, 4, 5, 6]]    m = 9    print(maxMatrix(A, m)) # This code is contributed by 29AjayKumar
     // C# to maximize matrix resultusing System;public class GFG {      static readonly int n = 4;  // utility function for maximize matrix result    static int maxMatrix(int [,]A, int M) {        int sum = 0, res = 0;        for (int i = 0; i < n; i++) {            for (int j = 0; j < n; j++) {                sum += A[i,j];            }        }          // diagonals below longest diagonal        // starting from last element of matrix        for (int j = n - 1; j > 0; j--) {            for (int i = 0; i < n - j; i++) {                if (sum > M) {                    A[n - 1 - i,j + i] = M;                    sum -= M;                } else {                    A[n - 1 - i,j + i] = sum;                    sum -= sum;                }            }        }          // diagonals above longest diagonal        for (int i = n - 1; i >= 0; i--) {            for (int j = 0; j <= i; j++) {                if (sum > M) {                    A[i - j,j] = M;                    sum -= M;                } else {                    A[i - j,j] = sum;                    sum -= sum;                }            }        }          // calculating result        for (int i = 0; i < n; i++) {            for (int j = 0; j < n; j++) {                res += (i + j + 2) * A[i,j];            }        }        return res;    }  // driver program    static public void Main() {        int [,]A= {{1, 2, 3, 4},        {5, 6, 7, 8},        {9, 1, 1, 2},        {3, 4, 5, 6}};        int m = 9;        Console.Write(maxMatrix(A, m));    }}  // This code is contributed by Rajput-Ji
<?php// PHP to maximize matrix result $n = 4; // function for maximize// matrix resultfunction maxMatrix($A, $M){    global $n;    $sum = 0; $res = 0;    for ($i = 0; $i < $n ; $i++)        for ($j = 0; $j < $n; $j++)            $sum += $A[$i][$j];     // diagonals below longest diagonal    // starting from last element of matrix    for ($j = $n - 1; $j > 0; $j--)    {        for ($i = 0; $i < $n - $j; $i++)        {            if ($sum > $M)            {                $A[$n - 1 - $i][$j + $i] = $M;                $sum -= $M;            }            else            {                $A[$n - 1 - $i][$j + i] = $sum;                $sum -= $sum;            }        }    }     // diagonals above longest diagonal    for ($i = $n - 1; $i >= 0; $i--)    {        for ($j = 0; $j <= $i; $j++)        {            if ($sum > $M)            {                $A[$i - $j][$j] = $M;                $sum -= $M;            }            else            {                $A[$i - $j][$j] = $sum;                $sum -= $sum;            }        }    }     // calculating result    for ($i = 0; $i < $n; $i++)    {        for ($j = 0; $j < $n; $j++)            $res += ($i + $j + 2) *                     $A[$i][$j];    }    return $res;}     // Driver Code    $A = array(array(1, 2, 3, 4),               array(5, 6, 7, 8),               array(9, 1, 1, 2),               array(3, 4, 5, 6));    $m = 9;    echo maxMatrix($A, $m);     // This code is contributed by anuj_67.?>
<script>    // Javascript to maximize matrix result         let n = 4;       // utility function for maximize matrix result    function maxMatrix(A, M) {        let sum = 0, res = 0;        for (let i = 0; i < n; i++) {            for (let j = 0; j < n; j++) {                sum += A[i][j];            }        }           // diagonals below longest diagonal        // starting from last element of matrix        for (let j = n - 1; j > 0; j--) {            for (let i = 0; i < n - j; i++) {                if (sum > M) {                    A[n - 1 - i][j + i] = M;                    sum -= M;                } else {                    A[n - 1 - i][j + i] = sum;                    sum -= sum;                }            }        }           // diagonals above longest diagonal        for (let i = n - 1; i >= 0; i--) {            for (let j = 0; j <= i; j++) {                if (sum > M) {                    A[i - j][j] = M;                    sum -= M;                } else {                    A[i - j][j] = sum;                    sum -= sum;                }            }        }           // calculating result        for (let i = 0; i < n; i++) {            for (let j = 0; j < n; j++) {                res += (i + j + 2) * A[i][j];            }        }        return res;    }         let A = [[1, 2, 3, 4],             [5, 6, 7, 8],             [9, 1, 1, 2],             [3, 4, 5, 6]];    let m = 9;    document.write(maxMatrix(A, m)); // This code is contributed by divyesh072019.</script>
Output:  
425
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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. 
vt_m
Rajput-Ji
29AjayKumar
divyesh072019
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Efficiently compute sums of diagonals of a matrix
Check for possible path in 2D matrix
Flood fill Algorithm - how to implement fill() in paint?
Zigzag (or diagonal) traversal of Matrix
Mathematics | L U Decomposition of a System of Linear Equations
Python program to add two Matrices
Unique paths in a Grid with Obstacles
A Boolean Matrix Question
Shortest distance between two cells in a matrix or grid
Breadth First Traversal ( BFS ) on a 2D array