1. 程式人生 > 其它 >【LeetCode】363. Max Sum of Rectangle No Larger Than K 矩形區域不超過 K 的最大數值和(Hard)(JAVA)

【LeetCode】363. Max Sum of Rectangle No Larger Than K 矩形區域不超過 K 的最大數值和(Hard)(JAVA)

技術標籤:Leetcodeleetcode演算法java面試動態規劃

【LeetCode】363. Max Sum of Rectangle No Larger Than K 矩形區域不超過 K 的最大數值和(Hard)(JAVA)

題目地址: https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/

題目描述:

Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is no larger than k.

Example:

Input: matrix = [[1,0,1],[0,-2,3]], k = 2
Output: 2 
Explanation:Because the sum of rectangle [[0, 1], [-2, 3]] is 2,
            and 2 is the max number no larger than k (k = 2).

Note:

  1. The rectangle inside the matrix must have an area > 0.
  2. What if the number of rows is much larger than the number of columns?

題目大意

給定一個非空二維矩陣 matrix 和一個整數 k,找到這個矩陣內部不大於 k 的最大矩形和。

說明:

  1. 矩陣內的矩形區域面積必須大於 0。
  2. 如果行數遠大於列數,你將如何解答呢?

解題方法

  1. 用的暴力求解方式,把所有的結果遍歷一遍
  2. note: 優化,可以把所有結果用一次遍歷求出來 sum ,然後求一個個矩陣的結果, sum[i][j] + sum[i - len][j - len] - sum[i][j - len] - sum[i - len][j]
class Solution {
    public int maxSumSubmatrix(int[][] matrix, int k) {
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                int[][] dp = new int[matrix.length][matrix[0].length];
                for (int x = i; x < matrix.length; x++) {
                    int sum = 0;
                    for (int y = j; y < matrix[0].length; y++) {
                        sum += matrix[x][y];
                        if (x == i) {
                            dp[x][y] = sum;
                        } else {
                            dp[x][y] = sum + dp[x - 1][y];
                        }
                        if (dp[x][y]<= k) max = Math.max(max, dp[x][y]);
                    }
                }
            }
        }
        return max;
    }
}

執行耗時:1383 ms,擊敗了6.47% 的Java使用者
記憶體消耗:39.4 MB,擊敗了11.07% 的Java使用者

歡迎關注我的公眾號,LeetCode 每日一題更新