#363
Max Sum of Rectangle No Larger Than K
HardArrayBinary SearchMatrixPrefix SumOrdered SetHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(m^2 * n^2) | O(m * n * log(n)) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(m * n * log(n))Space O(n)
The optimal solution uses a combination of prefix sums and a data structure to efficiently find the maximum sum rectangle that is less than or equal to k. This reduces the time complexity significantly.
⚙️
Algorithm
3 steps- 1Step 1: Iterate over all pairs of rows to define the top and bottom of the rectangle.
- 2Step 2: For each pair of rows, create an array that represents the sum of columns between these two rows.
- 3Step 3: Use a sorted data structure to find the maximum sum of subarrays that is less than or equal to k using binary search.
solution.py19 lines
1import bisect
2
3def maxSumSubmatrix(matrix, k):
4 m, n = len(matrix), len(matrix[0])
5 max_sum = float('-inf')
6 for r1 in range(m):
7 sums = [0] * n
8 for r2 in range(r1, m):
9 for c in range(n):
10 sums[c] += matrix[r2][c]
11 sorted_sums = [0]
12 curr_sum = 0
13 for sum_val in sums:
14 curr_sum += sum_val
15 idx = bisect.bisect_left(sorted_sums, curr_sum - k)
16 if idx < len(sorted_sums):
17 max_sum = max(max_sum, curr_sum - sorted_sums[idx])
18 bisect.insort(sorted_sums, curr_sum)
19 return max_sumℹ
Complexity note: The time complexity is O(m * n * log(n)) because we iterate through pairs of rows and use a sorted set to find the maximum sum efficiently. The space complexity is O(n) due to the array used for column sums.
- 1Understanding how to efficiently calculate subarray sums is crucial.
- 2Using sorted data structures can help in quickly finding the maximum sum that meets constraints.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.