博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode-Max Sum of Rectangle No Larger Than K
阅读量:5290 次
发布时间:2019-06-14

本文共 1992 字,大约阅读时间需要 6 分钟。

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:

  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?

Credits:

Special thanks to for adding this problem and creating all test cases.

Analysis:

Take the following analysis from https://discuss.leetcode.com/topic/48854/java-binary-search-solution-time-complexity-min-m-n-2-max-m-n-log-max-m-n

 

/* first  consider the situation matrix is 1D    we can save every sum of 0~i(0<=i
1 public class Solution { 2     public int maxSumSubmatrix(int[][] matrix, int k) { 3         if (matrix.length == 0 || matrix[0].length == 0) 4             return Integer.MIN_VALUE; 5  6         int res = Integer.MIN_VALUE; 7         int row = matrix.length; 8         int col = matrix[0].length; 9         int m = Math.min(row, col);10         int n = Math.max(row, col);11         boolean moreCol = (col > row);12 13         for (int i = 0; i < m; i++) {14             int[] sum = new int[n];15             for (int j = i; j >= 0; j--) {16                 int val = 0;17                 TreeSet
sumSet = new TreeSet
();18 sumSet.add(0);19 for (int l = 0; l < n; l++) {20 sum[l] = sum[l] + ((moreCol) ? matrix[j][l] : matrix[l][j]);21 val += sum[l];22 Integer other = sumSet.ceiling(val - k);23 if (other != null) {24 res = Math.max(res, val - other);25 }26 sumSet.add(val);27 }28 }29 }30 31 return res;32 }33 }

 

转载于:https://www.cnblogs.com/lishiblog/p/5687976.html

你可能感兴趣的文章
yield语句
查看>>
查看linux系统中占用cpu最高的语句
查看>>
[洛谷P1738]洛谷的文件夹
查看>>
ubuntu server设置时区和更新时间
查看>>
【京东咚咚架构演进】-- 好文收藏
查看>>
【HTML】网页中如何让DIV在网页滚动到特定位置时出现
查看>>
文件序列化
查看>>
Bootstrap--响应式导航条布局
查看>>
Learning Python 009 dict(字典)和 set
查看>>
JavaScript中随着鼠标拖拽而移动的块
查看>>
HDU 1021 一道水题
查看>>
The operation couldn’t be completed. (LaunchServicesError error 0.)
查看>>
php每天一题:strlen()与mb_strlen()的作用分别是什么
查看>>
工作中收集JSCRIPT代码之(下拉框篇)
查看>>
《转载》POI导出excel日期格式
查看>>
code异常处理
查看>>
git - 搭建最简单的git server
查看>>
会话控制
查看>>
推荐一款UI设计软件Balsamiq Mockups
查看>>
Linux crontab 命令格式与详细例子
查看>>