LeetCode 363. Max Sum of Rectangle No Larger Than K

原题链接在这里:https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/

题目:

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.length
  • n == matrix[i].length
  • 1 <= m, n <= 100
  • -100 <= matrix[i][j] <= 100
  • -105 <= k <= 105

Follow up: What if the number of rows is much larger than the number of columns?

题解:

2D Kadane's algorithm.

The outter loop should be min of (m, n).

Time Complexity: O(x^2 * y * logy). x = min(m, n). y = max(m, n).

Space: O(y).

AC Java:

 1 class Solution {
 2     public int maxSumSubmatrix(int[][] matrix, int k) {
 3         // 2D Kadane's algorithm
 4         if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
 5             return 0;
 6         }
 7         
 8         int m = matrix.length;
 9         int n = matrix[0].length;
10         int res = Integer.MIN_VALUE;
11         
12         // outter loop should be min(m, n).
13         for(int left = 0; left < n; left++){
14             int [] sums = new int[m];
15             for(int right = left; right < n; right++){
16                 // Update sums[i] as sum of row i from left to right.
17                 for(int i = 0; i < m; i++){
18                     sums[i] += matrix[i][right];
19                 }
20                 
21                 // Find no larger than k with sums.
22                 // Find the max of currentSum - prevSum <= k
23                 // Thus currentSum - k <= preSum, find ceiling of currentSum - k
24                 TreeSet<Integer> ts = new TreeSet<>();
25                 ts.add(0);
26                 int curSum = 0;
27                 for(int num : sums){
28                     curSum += num;
29                     Integer preSum = ts.ceiling(curSum - k);
30                     if(preSum != null){
31                         res = Math.max(res, curSum - preSum);
32                     }
33                     
34                     ts.add(curSum);
35                 }
36                 
37             }
38         }
39         
40         return res;
41     }
42 }

类似Maximum Subarray.

posted @ 2022-10-03 16:11  Dylan_Java_NYC  阅读(17)  评论(0编辑  收藏  举报