[TODO] LeetCode #363: Max Sum of Rectangle No Larger Than K
来源:互联网 发布:个人知识管理系统java 编辑:程序博客网 时间:2024/06/05 16:16
Problem Statement
(Source) 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
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?
Analysis
Be naive first. Then optimise.
Tags:Dynamic Programming
, Binary Search
.
First Try
TLE
Time complexity is
class Solution(object): def maxSumSubmatrix(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ if not matrix or not matrix[0]: return 0 n, m = len(matrix), len(matrix[0]) dp = [[0 for j in xrange(m + 1)] for i in xrange(n + 1)] for i in xrange(1, n + 1): for j in xrange(1, m + 1): dp[i][j] = dp[i][j - 1] + dp[i - 1][j] - dp[i - 1][j - 1] + matrix[i - 1][j -1] res = float('-inf') for row1 in xrange(1, n + 1): for row2 in xrange(row1, n + 1): for col1 in xrange(1, m + 1): for col2 in xrange(col1, m + 1): temp_sum = dp[row2][col2] - dp[row2][col1 - 1] - dp[row1 - 1][col2] + dp[row1 - 1][col1 - 1] if temp_sum < k: res = max(res, temp_sum) elif temp_sum == k: return k return res
TODO!
0 0
- [TODO] LeetCode #363: Max Sum of Rectangle No Larger Than K
- leetcode(363):Max Sum of Rectangle No Larger Than K
- Leetcode Max Sum of Rectangle No Larger Than K
- [leetcode] 363. Max Sum of Rectangle No Larger Than K
- leetcode.363. Max Sum of Rectangle No Larger Than K
- [LeetCode]--363. Max Sum of Rectangle No Larger Than K
- leetcode-363. Max Sum of Rectangle No Larger Than K
- [LeetCode]Max Sum of Rectangle No Larger Than K
- [LeetCode] Max Sum of Rectangle No Larger Than K
- Leetcode 363. Max Sum of Rectangle No Larger Than K
- 【Leetcode】363. Max Sum of Rectangle No Larger Than K
- 【Leetcode】Max Sum of Rectangle No Larger Than K
- [leetcode]363. Max Sum of Rectangle No Larger Than K
- leetcode 363. Max Sum of Rectangle No Larger Than K
- [leetcode-363]Max Sum of Rectangle No Larger Than K(java)
- LeetCode 363 Max Sum of Rectangle No Larger Than K (二分)
- Leetcode 363 - Max Sum of Rectangle No Larger Than K(前缀和+二分)
- 363. Max Sum of Rectangle No Larger Than K
- 算法日记(Java实现)第20160904(6)期——CCF俄罗斯方块
- 数组中a与&a的区别
- 网易有道2017内推编程题 队列操作(映射)
- 在ScrollView中加入listview后的处理
- LeetCode之Maximum Depth of Binary Tree(Java版)
- [TODO] LeetCode #363: Max Sum of Rectangle No Larger Than K
- Longest Substring with At Most Two Distinct Characters
- 状态模式(java版)
- JNDI 是什么(Java Naming and Directioy Interface)
- hust sci列表
- AndroidStudio——今日头条(可以实时获取数据的app)
- 看电影 【NOIP2016提高A组模拟9.3】
- 【NOIP2016提高A组模拟9.3】看电影
- (25)HTML5-初识jQuery