[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 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?

Analysis

Be naive first. Then optimise.


Tags:Dynamic Programming, Binary Search.

First Try

TLE Time complexity is O(m2n2).

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
原创粉丝点击