
Sponsored
Sponsored
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
The Python solution uses a list to store previously computed values and recursively calculates results as needed.
The C solution iteratively calculates Fibonacci numbers using constant space, which makes it efficient for larger values of n.