leetcode 363. 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:

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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution(object):
def maxSubArray(self,nums,k):

cumset=[]
cumset.append(0)
maxsum=-1<<32
cursum=0
for i in range(len(nums)):
cursum+=nums[i]
# find the lower bound of the index
idx=bisect.bisect_left(cumset,cursum-k)
# find max in sum[right]-sum[left]<=k
if 0<=idx<len(cumset):
maxsum=max(maxsum,cursum-cumset[idx])
# using insort instead of append since bisect_left reason
bisect.insort(cumset,cursum)
return maxsum
def maxSumSubmatrix(self,matrix, k):

if not matrix or not matrix[0]:
return 0
row,col=len(matrix),len(matrix[0])
res=-(1<<32)
for left in range(col):
cursums=[0 for _ in range(row)]
right=left
while right<col:
for i in range(row):
cursums[i]+=matrix[i][right]
curarrmax=self.maxSubArray(cursums,k)
res=max(res,curarrmax)
right+=1

return res