
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.
1import bisect
2
3def maxSumSubmatrix(matrix, k):
4 if not matrix or not matrix[0]: return 0
5 max_sum = float('-inf')
6 rows, cols = len(matrix), len(matrix[0])
7
8 for left in range(cols):
9 row_sum = [0] * rows
10 for right in range(left, cols):
11 for r in range(rows):
12 row_sum[r] += matrix[r][right]
13 max_sum = max(max_sum, maxSumNoLargerThanK(row_sum, k))
14
15 return max_sum
16
17
18def maxSumNoLargerThanK(nums, k):
19 accu_sum, max_sum = 0, float('-inf')
20 accu_sums = [0]
21 for num in nums:
22 accu_sum += num
23 i = bisect.bisect_left(accu_sums, accu_sum - k)
24 if i < len(accu_sums):
25 max_sum = max(max_sum, accu_sum - accu_sums[i])
26 bisect.insort(accu_sums, accu_sum)
27 return max_sum
28The Python implementation uses a 2D prefix sum to convert the problem into finding a subarray sum no larger than k. We iterate over left and right column boundaries and compute row-wise sums in between. Then maxSumNoLargerThanK finds the maximum subarray sum no larger than k in these running row sums using a binary search approach (with the help of Python's bisect library) to maintain the cumulative sum.
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#include <vector>
using namespace std;
int fib(int n, vector<int>& memo) {
if (n <= 1) return n;
if (memo[n] != -1) return memo[n];
return memo[n] = fib(n-1, memo) + fib(n-2, memo);
}
int main() {
int n = 10; // Example
vector<int> memo(n + 1, -1);
cout << fib(n, memo) << endl;
return 0;
}The C++ solution uses a vector for memoization and recursively computes Fibonacci numbers, storing intermediate results for efficiency.
The C solution iteratively calculates Fibonacci numbers using constant space, which makes it efficient for larger values of n.