
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#
The C solution initializes a memo array to store intermediate results. The solve function checks if the value is already computed to avoid recalculating it, and recursively calculates values as needed.
The C solution iteratively calculates Fibonacci numbers using constant space, which makes it efficient for larger values of n.