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?

思路:find the max sum rectangle in 2D array https://www.youtube.com/watch?v=yCQN096CwWM 

核心思想就是:每列column,从左向右投影,left, right, 是左右边界,然后sums[n] 是长度为row的投影sum,也就是prefixsum。每次移动left, right,计算出sums array之后,问题就转换为,在一个array里面,找subarray sum最接近K的sum;这里用了treeset ceiling是第一个大于input的value,num >= currsum - k; currsum - num <= k; 每次update这个currsum - num  就可以了。currsum 是累加的sum;

注意:currusm - num 代表的就是下面的block的matrix;set.add(0); // 需要padding,是为了解决只有一个row value的情况;比如说cursum = 10, k = 10,那么就只有一个sum的话,就是要返回10,如果没有0,就会返回null,得不到sum就等于k的情况;

class Solution {
    public int maxSumSubmatrix(int[][] matrix, int k) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return 0;
        }
        
        int n = matrix.length;
        int m = matrix[0].length;
        int result = Integer.MIN_VALUE;
        
        for(int left = 0; left < m; left++) {
            int[] arr = new int[n];
            for(int right = left; right < m; right++) {
                for(int i = 0; i < n; i++) {
                    arr[i] += matrix[i][right];
                }
                
                TreeSet<Integer> treeset = new TreeSet<>();
                // 需要padding,是为了解决只有一个row value的情况;
                // 比如说cursum = 10, k = 10,那么就只有一个sum的话,就是要返回10,如果没有0,就会返回null,得不到sum就等于k的情况;
                treeset.add(0);
                int cursum = 0;
                
                for(int prefixsum: arr) {
                    cursum += prefixsum;
                    // num >= cursum - k;
                    // k >= cursum - num;
                    Integer num = treeset.ceiling(cursum - k);
                    if(num != null) {
                        // k >= cursum - num;
                        // currusm - num 代表的就是下面的block的matrix;
                        result = Math.max(result, cursum - num);
                    }
                    treeset.add(cursum);
                }
            }
        }
        return result;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sure, I can help you with that! Here is a possible implementation of the Rectangle class in Python: ```python class Rectangle: def __init__(self, x1, y1, x2, y2, x3, y3, x4, y4): self.set_coordinates(x1, y1, x2, y2, x3, y3, x4, y4) def set_coordinates(self, x1, y1, x2, y2, x3, y3, x4, y4): # Verify that all coordinates are in the first quadrant if x1 < 0 or y1 < 0 or x2 < 0 or y2 < 0 or x3 < 0 or y3 < 0 or x4 < 0 or y4 < 0: raise ValueError("All coordinates must be in the first quadrant") # Verify that no coordinate is larger than 20.0 if x1 > 20.0 or y1 > 20.0 or x2 > 20.0 or y2 > 20.0 or x3 > 20.0 or y3 > 20.0 or x4 > 20.0 or y4 > 20.0: raise ValueError("No coordinate can be larger than 20.0") # Verify that the coordinates specify a rectangle if not self.is_rectangle(x1, y1, x2, y2, x3, y3, x4, y4): raise ValueError("The coordinates do not specify a rectangle") # Store the coordinates as a list of tuples self.coordinates = [(x1, y1), (x2, y2), (x3, y3), (x4, y4)] def is_rectangle(self, x1, y1, x2, y2, x3, y3, x4, y4): # Check if the four sides have equal length and opposite sides are parallel return self.distance(x1, y1, x2, y2) == self.distance(x3, y3, x4, y4) and \ self.distance(x2, y2, x3, y3) == self.distance(x4, y4, x1, y1) and \ abs((y2 - y1) * (y4 - y3) + (x2 - x1) * (x4 - x3)) < 1e-10 def distance(self, x1, y1, x2, y2): # Calculate the distance between two points return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5 def length(self): # Calculate the length of the rectangle (longer dimension) return max(self.distance(self.coordinates[0][0], self.coordinates[0][1], self.coordinates[1][0], self.coordinates[1][1]), self.distance(self.coordinates[1][0], self.coordinates[1][1], self.coordinates[2][0], self.coordinates[2][1])) def width(self): # Calculate the width of the rectangle (shorter dimension) return min(self.distance(self.coordinates[0][0], self.coordinates[0][1], self.coordinates[1][0], self.coordinates[1][1]), self.distance(self.coordinates[1][0], self.coordinates[1][1], self.coordinates[2][0], self.coordinates[2][1])) def area(self): # Calculate the area of the rectangle return self.length() * self.width() def perimeter(self): # Calculate the perimeter of the rectangle return 2 * self.length() + 2 * self.width() def is_square(self): # Check if the rectangle is a square (equal length and width) return abs(self.length() - self.width()) < 1e-10 ``` Here is an example of how to use this class: ```python # Create a rectangle with coordinates (0, 0), (0, 5), (10, 5), (10, 0) rect = Rectangle(0, 0, 0, 5, 10, 5, 10, 0) # Print the length, width, area, perimeter, and whether it's a square print(rect.length()) # Output: 10.0 print(rect.width()) # Output: 5.0 print(rect.area()) # Output: 50.0 print(rect.perimeter()) # Output: 30.0 print(rect.is_square()) # Output: False ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值