Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the matrix such that its sum is no larger than k.
It is guaranteed that there will be a rectangle with a sum no larger than k.
Example 1:
Input: matrix = [[1,0,1],[0,-2,3]], k = 2 Output: 2 Explanation: Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).
Example 2:
Input: matrix = [[2,2,-1]], k = 3 Output: 3
Constraints:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 100-100 <= matrix[i][j] <= 100-105 <= k <= 105Follow up: What if the number of rows is much larger than the number of columns?
The challenge in #363 Max Sum of Rectangle No Larger Than K is finding the maximum sum of any sub-rectangle in a matrix that does not exceed k. A brute force approach would enumerate all possible rectangles, but that leads to very high time complexity.
An efficient strategy reduces the 2D problem into multiple 1D subarray problems. We fix pairs of columns (or rows) and compress the matrix between them into a temporary array representing cumulative row sums. The task then becomes finding the maximum subarray sum in this array that is no larger than k.
To solve this efficiently, we use prefix sums along with an ordered set (or balanced BST). By maintaining sorted prefix sums, we can quickly search for the smallest prefix that satisfies the constraint using binary search. This allows us to evaluate candidate subarrays efficiently.
The overall complexity becomes significantly better than brute force, making it feasible for interview constraints.
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Row/Column Compression with Prefix Sum + Ordered Set | O(min(m,n)^2 * max(m,n) log(max(m,n))) | O(max(m,n)) |
Tushar Roy - Coding Made Simple
This approach involves calculating the prefix sum for every column and iterating over pairs of row indices to form vertical strips. The idea is derived from simplifying the multidimensional problem to a manageable form by transforming it into a 1D problem with the help of prefix sums and leveraging subarray sum computation techniques.
Time Complexity: O(n^2 * m log m), where m = num of rows and n = num of columns. Space Complexity: O(m) for storing row sums.
1#include <vector>
2#include <set>
3
4using namespace std;
5
6int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
7 if (matrix.empty()) return 0;
8 int maxSum = INT_MIN, rows = matrix.size(), cols = matrix[0].size();
9
10 for (int left = 0; left < cols; ++left) {
11 vector<int> rowSum(rows, 0);
12 for (int right = left; right < cols; ++right) {
13 for (int r = 0; r < rows; ++r) {
14 rowSum[r] += matrix[r][right];
15 }
16 maxSum = max(maxSum, maxSumNoLargerThanK(rowSum, k));
17 }
18 }
19 return maxSum;
20}
21
22int maxSumNoLargerThanK(vector<int>& nums, int k) {
23 set<int> accuSet;
24 accuSet.insert(0);
25 int sum = 0, maxSum = INT_MIN;
26 for (int num : nums) {
27 sum += num;
28 auto it = accuSet.lower_bound(sum - k);
29 if (it != accuSet.end()) maxSum = max(maxSum, sum - *it);
30 accuSet.insert(sum);
31 }
32 return maxSum;
33}In the C++ version, we iterate over pairs of columns and calculate running sums in the form of rowSum. For each set of rowSum, we identify the max subarray no larger than k using a set to maintain seen cumulative sums and binary search for possible subarrays starting indices using std::set.lower_bound.
This approach uses recursion to solve the problem by breaking it down into smaller subproblems and storing the results of these subproblems to avoid redundant calculations. Hence, it combines recursion with memoization.
Time Complexity: O(n)
Space Complexity: O(n) due to the memoization array
1
class Program {
static int[] memo;
static int Fib(int n) {
if (n <= 1) return n;
if (memo[n] != -1) return memo[n];
memo[n] = Fib(n-1) + Fib(n-2);
return memo[n];
}
static void Main() {
int n = 10; // Example
memo = new int[n + 1];
for (int i = 0; i <= n; i++) memo[i] = -1;
Console.WriteLine(Fib(n));
}
}Watch expert explanations and walkthroughs
Practice problems asked by these companies to ace your technical interviews.
Explore More ProblemsJot down your thoughts, approach, and key learnings
Prefix sums allow quick computation of subarray sums by subtracting earlier cumulative sums from the current total. This helps convert the problem of checking all subarrays into a faster search problem using stored prefix values.
Yes, this problem is considered a challenging matrix and prefix sum problem and has appeared in high-level technical interviews. It tests understanding of multidimensional optimization, prefix sums, and efficient searching with ordered data structures.
The optimal approach compresses the 2D matrix into multiple 1D arrays by fixing column or row boundaries. For each compressed array, prefix sums and an ordered set are used to efficiently find the maximum subarray sum that does not exceed k.
An ordered set or balanced binary search tree is commonly used to store prefix sums in sorted order. This structure enables efficient binary search to find the smallest prefix sum that satisfies the constraint for the current running sum.
The C# solution utilizes an array for memoization and solves the Fibonacci sequence recursively while storing results to improve efficiency.
The C solution iteratively calculates Fibonacci numbers using constant space, which makes it efficient for larger values of n.