forked from das-jishu/algoexpert-data-structures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaximum-sum-submatrix.py
43 lines (30 loc) · 1.15 KB
/
maximum-sum-submatrix.py
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
35
36
37
38
39
40
41
42
43
# MAXIMUM SUM SUBMATRIX
# O(W * H) time and space
def maximumSumSubmatrix(matrix, size):
# Write your code here.
sums = createSumMatrix(matrix)
maxSum = float("-inf")
for row in range(size - 1, len(matrix)):
for col in range(size - 1, len(matrix[row])):
total = sums[row][col]
touchesTopBorder = row - size < 0
if not touchesTopBorder:
total -= sums[row - size][col]
touchesLeftBorder = col - size < 0
if not touchesLeftBorder:
total -= sums[row][col - size]
if not touchesTopBorder and not touchesLeftBorder:
total += sums[row - size][col - size]
maxSum = max(maxSum, total)
return maxSum
def createSumMatrix(matrix):
sums = [[0 for _ in range(len(matrix[row]))] for row in range(len(matrix))]
sums[0][0] = matrix[0][0]
for idx in range(1, len(matrix[0])):
sums[0][idx] = sums[0][idx - 1] + matrix[0][idx]
for idx in range(1, len(matrix)):
sums[idx][0] = sums[idx - 1][0] + matrix[idx][0]
for row in range(1, len(matrix)):
for col in range(1, len(matrix[row])):
sums[row][col] = sums[row - 1][col] + sums[row][col - 1] - sums[row - 1][col - 1] + matrix[row][col]
return sums