![]() |
VOOZH | about |
Given a matrix of m*n order, the task is to find the maximum difference between two rows Rj and Ri such that i < j, i.e., we need to find maximum value of sum(Rj) - sum(Ri) such that row i is above row j.
Examples:
Input : mat[5][4] = {{-1, 2, 3, 4},
{5, 3, -2, 1},
{6, 7, 2, -3},
{2, 9, 1, 4},
{2, 1, -2, 0}}
Output: 9
// difference of R3 - R1 is maximum
A simple solution for this problem is to one by one select each row, compute sum of elements in it and take difference from sum of next rows in forward direction. Finally return the maximum difference. Time complexity for this approach will be O(n*m2).
An efficient solution solution for this problem is to first calculate the sum of all elements of each row and store them in an auxiliary array rowSum[] and then calculate maximum difference of two elements max(rowSum[j] - rowSum[i]) such that rowSum[i] < rowSum[j] in linear time. See this article. In this method, we need to keep track of 2 things:
Implementation:
9
Time Complexity : O(m*n)
Auxiliary Space : O(m)