Maximum sum Rectangle | Practice | GeeksforGeeks

Given a 2D matrix M of dimensions RxC. Find the maximum sum submatrix in it.
Example 1:
Input:
R=4
C=5
M=[[1,2,-1,-4,-20],
[-8,-3,4,2,1],
[3,8,10,1,3],
[-4,-1,1,7,-6]]
Output:
29
Explanation:
The matrix is as follows and the
blue rectangle denotes the maximum sum
rectangle.


Example 2:
Input:
R=2
C=2
M=[[-1,-2],[-3,-4]]
Output:
-1
Explanation:
Taking only the first cell is the 
optimal choice.

Your Task:
You don't need to read input or print anything. Your task is to complete the function maximumSumRectangle() which takes the number R, C, and the 2D matrix M as input parameters and returns the maximum sum submatrix.

Expected Time Complexity:O(R*R*C)
Expected Auxillary Space:O(R*C)
 
Constraints:
1<=R,C<=500
-1000<=M[i][j]<=1000
0
anutigerin 9 hours
        int ans = 0;
        int ans1 = -1000;
        for(int i = 0 ; i < R ; i ++){
            for(int j = 0 ;  j < C ; j ++){
                ans1 = max(ans1,M[i][j]);
            }
        }
        for(int i = 0 ; i < C ; i ++){
            vector< int > dp(R,0);
            for(int j = i ; j < C ; j++){
                for(int k = 0 ; k < R; k ++){
                    dp[k] += M[k][j];
                }
                int res = 0;
                for(int k = 0 ; k < R ; k ++){
                    res += dp[k];
                    if(res < 0) res  = 0;
                    ans = max(ans,res);
                }
            }
        }
        if(ans == 0) return ans1;
        return ans;
0
wjyjobs1 week ago
class Solution:
    def maximumSumRectangle(self,R,C,M):
        for r in M:
            for i in range(1, C):
                r[i] += r[i-1]
               
        ans = float('-inf') 
        for l in range(C):
            for r in range(l, C):
                running = 0
                for i in range(R):
                    v = M[i][r]
                    if l > 0:
                        v -= M[i][l-1]
                    running += v
                    ans = max(ans, running)
                    if running < 0:
                        running = 0
        return ans
+1
abhishekkaswan1 week ago
Can do it using O(C*C*R) like this also , really easy C++ solution
int kadanel(vector<int> &res)
    {
        int max1=INT_MIN,max2=0;
        for(int i=0;i<res.size();i++)
        {
            max2+=res[i];
            if(max1<max2)
                max1=max2;
            if(max2<0)
                max2=0;
                
        }
        return max1;
    }
    int maximumSumRectangle(int r, int c, vector<vector<int>> M) {
        int ans=INT_MIN;
        for(int i=0;i<c;i++)
        {
            vector<int> res(r);
            for(int j=i;j<c;j++)
            {
                for(int k=0;k<r;k++)
                {
                    res[k]+=M[k][j];
                }
                ans=max(ans,kadanel(res));
            }
            
        }
        return ans;
    }
-1
subhashishde081 week ago
class Solution {
  public:
  int kadane(vector<int> v,int n){
    int ma = INT_MIN;
    int untill = 0;
    for(int i=0;i<n;i++){
        untill += v[i];
        if(untill>ma) ma= untill;
        if(untill<0) untill = 0;
    }
    return ma;
   }
    int maximumSumRectangle(int m, int n, vector<vector<int>> M) {
        // code here
        int maxi = INT_MIN;
        for(int i=0;i<m;i++){
            vector<int> res(n,0);
            for(int j=i;j<m;j++){
                for(int col=0;col<n;col++){
                    res[col] += M[j][col];
                }
                maxi = max(maxi,kadane(res,n));
            }
        }
        return maxi;
    }
};
 
0
jrchoudhary24101 week ago
Simple and easy || prefix sum || kadane's 
class Solution {
    int maximumSumRectangle(int r, int c, int m[][]) {
        // code here
        int max = Integer.MIN_VALUE;
        int [] dp = new int[c];
        for(int i=0;i<r;i++){
            for(int j=i;j<r;j++){
               for(int k=0;k<c;k++){
                   dp[k] += m[j][k]; 
               } 
               max = Math.max(max, kadane(dp));
            }
            Arrays.fill(dp, 0);
        }
        return max;
    }
    public static int kadane(int [] dp){
        int sum=dp[0], max=dp[0];
        for(int i=1;i<dp.length;i++){
            sum+= dp[i];
            if(sum<dp[i])
                sum = dp[i];
            max = Math.max(sum, max);
        }
        return max;
    }
}
0
jrchoudhary2410
This comment was deleted.
+4
harsh63101 week ago
Easy to Understand, O(C*C*R) Time and O(R*C) Space
Really great problem, can be solved by selecting starting and ending columns ( O(C*C) ) then using kadanes algorithm for finding largest sum of contiguous rows in between those 2 columns we selected.
Sum of a row can be found with pre-calculations, thus helping us find Largest Sum of contiguous rows in O(R).....bringing the total time complexity to O(R*C*C).
We can do same for columns instead of rows to make time complexity O(C*R*R) interchangeably.
Code:
class Solution {
  public:
    int maximumSumRectangle(int r, int c, vector<vector<int>>& m) {
        vector< vector<int> > rsum(m.begin(),m.end()) ;
        
        for(int i=0 ; i<r ; i++)
            for(int j=1 ; j<c ; j++)
                rsum[i][j] += rsum[i][j-1] ; 
                
        int ans = INT_MIN ;
        
        for(int sc=0 ; sc<c ; sc++){
            for(int ec=sc ; ec<c ; ec++){
            
                int mrs = 0 , crsum = 0 ; 
                for(int i=0 ; i<r ; i++){
                    crsum += rsum[i][ec]-(sc == 0 ? 0 : rsum[i][sc-1] ) ;
                    ans = max(ans,crsum - mrs) ;
                    mrs = min(mrs,crsum) ; 
                }
                
            }
        }
        
        return ans ;
    }
};

0
6288261 week ago
Use prefix-sum array and Kadane's algorithm.
Nice and clear.
vector<vector<int>> acc(R, vector<int>(C + 1));
int glo = INT_MIN;

// prefix-sum array
for (int i = 0; i < R; ++i)
	for (int j = 0; j < C; ++j)
		acc[i][j + 1] = acc[i][j] + M[i][j];
		
for (int i = 0; i < C; ++i)
{
	for (int j = i; j < C; ++j)
	{
		// kadane
		int loc = 0;
		
		for (int k = 0; k < R; ++k)
		{
			// use prefix-sum to avoid repeated accumulation.
			loc += acc[k][j + 1] - acc[k][i]; 
			glo = max(glo, loc);
			loc = max(loc, 0);
		}
	}
}

return glo;
+1
priyankapardesiramachander1 week ago
My solution in C# → https://github.com/ramacpr/G4G_DailyCodingProblems/tree/master/April15_2022/MaxSumRectangle 
0
akshayadivarekar7771 week ago
//JAVA Solution
// Its just KADANE
class Solution {
   int maximumSumRectangle(int R, int C, int M[][]) {
       // code here
       
       int max = 0;
       int maxop=Integer.MIN_VALUE;
       int[] dp = new int[R];
       
       for(int i=0;i<C;i++)
       {
           
           for(int j=i;j<C;j++)
           {
               for(int k=0;k<dp.length;k++)
               {
                   dp[k]+=M[k][j];
                   maxop = Math.max(maxop,M[k][j]);
               }
               max = Math.max(max,kadane(dp));
               
           }
           Arrays.fill(dp,0);
       }
       
       return max==0? maxop:max;
       
   }
   
   public int kadane(int[] arr)
   {
       
       int cur=0;
       int max=0;
       for(int i:arr)
       {
           cur+=i;
           max = Math.max(max,cur);
           if(cur<0)
           cur=0;
       }
       return max;
       
       
   }
}; 
 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.