Max Sum of Rectangle No Larger Than K

本文介绍了一个算法问题:在一个二维矩阵中找到最大和的矩形区域,该区域的和不大于给定整数K。通过使用动态规划的方法,文章详细解释了如何有效地解决这一问题,并给出了具体的Java实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


title: 363.Max Sum of Rectangle No Larger Than K
date: 2018-2-7 21:48:38
categories:
- algorithm
tags:
- algorithm
- java

- leetcode

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:
Given matrix = [
[1, 0, 1],
[0, -2, 3]
]
k = 2

The answer is 2. Because the sum of rectangle [[0, 1], [-2, 3]] is 2 and 2 is the max number no larger than k (k = 2).

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

按照[LeetCode] Range Sum Query 2D - Immutable 二维区域和检索 - 不可变 一样的方法,使用O(n^4)复杂度得出答案。

public static int maxSumSubmatrix(int[][] matrix, int k) {
            if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
                return -1;
            }
            // DP数组保存的是右下角和左上角之间区域的和
            int[][] dp = new int[matrix.length + 1][matrix[0].length + 1];
//          dp[0][0] = matrix[0][0];
            for (int i = 1; i <= matrix.length; i++) {
                for (int j = 1; j <= matrix[0].length; j++) {
                    dp[i][j] = dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1] + matrix[i - 1][j - 1];
                }
            }
            int res = Integer.MIN_VALUE;
            // 这里O(n^4)应该是可以改善的,,,,,,,,暂时还没注意。
            for (int i = 1; i <= matrix.length; i++) {
                for (int j = 1; j <= matrix[0].length; j++) {
                    for (int h = i; h <= matrix.length; h++) {
                        for (int s = j; s <= matrix[0].length; s++) {
                            if (sumRegion(i, j, h, s, dp) == k) {
                                return k;
                            }
                            if (sumRegion(i, j, h, s, dp) < k) {
                                res = Math.max(res, sumRegion(i, j, h, s, dp));
                            }
                        }
                    }
                }
            }
            // 没有得到小于k的res
            if (res == Integer.MIN_VALUE) {
                return -1;
            }
            return res;
     }
     // 求区域和的函数
     public static int sumRegion(int row1, int col1, int row2, int col2, int[][] dp) {

            return dp[row2][col2] - dp[row2][col1 - 1] - dp[row1 - 1][col2] + dp[row1 - 1][col1 - 1];

     }

Range Sum Query 2D - Immutable 和上面那个题目是相同的思想

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).

Range Sum Query 2D
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.

Example:

Given matrix = [
[3, 0, 1, 4, 2],
[5, 6, 3, 2, 1],
[1, 2, 0, 1, 5],
[4, 1, 0, 1, 7],
[1, 0, 3, 0, 5]
]

sumRegion(2, 1, 4, 3) -> 8
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12

Note:

You may assume that the matrix does not change.
There are many calls to sumRegion function.
You may assume that row1 ≤ row2 and col1 ≤ col2.
public class NumMatrix {
    private int[][] dp;
    public NumMatrix(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return ;
        }
        int rows = matrix.length;
        int cols = matrix[0].length;
        dp = new int[rows + 1][cols + 1];
        dp[0][0] = matrix[0][0];
//        for (int i = 1; i < rows; i++) {
//          dp[i][0] = matrix[i][0] + dp[i - 1][0];
//        }
//        for (int i = 1; i < cols; i++) {
//          dp[0][i] = matrix[0][i] + dp[0][i - 1];
//        }

        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= cols; j++) {
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1] + matrix[i - 1][j - 1];
            }
        }
    }

    public int sumRegion(int row1, int col1, int row2, int col2) {

        return dp[row2 + 1][col2 + 1] - dp[row2 + 1][col1] - dp[row1][col2 + 1] + dp[row1][col1];

    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[][] matrix = {
                        {3, 0, 1, 4, 2},
                        {5, 6, 3, 2, 1},
                        {1, 2, 0, 1, 5},
                        {4, 1, 0, 1, 7},
                        {1, 0, 3, 0, 5}
        };
        NumMatrix matrix2 = new NumMatrix(matrix);
        System.out.println(matrix2.sumRegion(1,2,2,4));
    }

}
这个错误信息表示你正在尝试访问名为 `get` 的属性或方法,但是 `Rectangle` 对象并没有定义这样的属性或方法。 ### 可能的原因及解决办法: 1. **拼写错误**: - 检查是否有拼写错误。例如,你可能是想调用其他名称的方法,如 `area()` 或者 `perimeter()` 等等。 2. **类定义缺失**: - 如果你需要使用 `get` 方法,请确认是否已经在这个类里实现了它。如果确实需要添加该功能,可以在 `Rectangle` 类中增加相应的函数定义,比如 `def get(self): ...` 3. **理解对象模型**: - 了解 Python 中如何正确地向自定义类型(即用户创建的类实例)添加数据成员和行为是非常重要的。对于矩形类来说,通常会包含像宽度、高度之类的字段以及计算面积或周长之类的方法。 4. **检查文档/库版本**: - 假设你在使用某个特定图形处理包里的 Rectangle 实现,则应查阅官方手册确保自己所使用的 API 是正确的,并注意可能存在不同版本之间的差异导致某些特性不再可用。 5. **调试技巧**: - 使用 IDE 内置工具或者 print(dir(rectangle_instance)) 来查看当前 rectangle 实例所有支持的操作列表;也可以利用帮助系统获取更多细节:help(type(your_rectangle_object)) #### 示例修正代码片段 如果你有一个简单的 Rectangle 类并且想要获得其尺寸信息,可以按如下方式修改: ```python class Rectangle: def __init__(self, width=0, height=0): self.width = width self.height = height # 添加 getter 方法 def get_dimensions(self): return {"width": self.width, "height": self.height} ``` 然后你可以通过 `rectangle.get_dimensions()` 调用来取得宽高值了。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值