Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Max Sum of Rectangle No Larger Than K in C++
Suppose we have a 2D matrix, and an integer k. We have to find the max sum of a rectangle in the matrix, such that its sum is not greater than k. So, if the input is like −
| 1 | 0 | 1 |
| 0 | -3 | 2 |
And k = 3, then the output will be 3, as the sum of marked rectangle is 3.
To solve this, we will follow these steps −
- Define a function maxSumSubmatrix(), this will take one 2D array matrix and k,
- n := row number, m := column number
- ans := -inf
- for initialize l := 0, when l < m, update (increase l by 1), do −
- Define an array rowSum of size n
- for initialize r := l, when r < m, update (increase r by 1), do −
- for initialize i := 0, when i < n, update (increase i by 1), do −
- rowSum[i] := rowSum[i] + matrix[i, r]
- Define one set s
- insert 0 into s
- currSum := 0
- for initialize i := 0, when i < n, update (increase i by 1), do −
- currSum := currSum + rowSum[i]
- it := first element of set that is not greater than currSum – k
- if it is not equal to last element of s, then −
- ans := maximum of ans and (currSum - it)
- insert currSum into s
- for initialize i := 0, when i < n, update (increase i by 1), do −
- return ans
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
int n = matrix.size();
int m = matrix[0].size();
int ans = INT_MIN;
for(int l = 0; l < m; l++){
vector <int> rowSum(n);
for(int r = l; r < m; r++){
for(int i = 0; i < n; i++)rowSum[i] += matrix[i][r];
set < int > s;
s.insert(0);
int currSum = 0;
for(int i = 0; i < n; i++){
currSum += rowSum[i];
set <int> :: iterator it = s.lower_bound(currSum - k);
if(it != s.end()){
ans = max(ans, (currSum - *it));
}
s.insert(currSum);
}
}
}
return ans;
}
};
main(){
Solution ob;
vector<vector<int>> v = {{1,0,1},{0,-3,2}};
cout << (ob.maxSumSubmatrix(v, 3));
}
Input
[{1,0,1},{0,-3,2}]
3
Output
3
Advertisements