Skip to content

Commit e1508e2

Browse files
committed
Merge pull request mission-peace#90 from orsenthil/python/sub_rectangular_max_sum
Sub Rectangular Matrix of maximum sum.
2 parents 4d5408a + 6ec1091 commit e1508e2

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
"""
2+
Problem Statement
3+
=================
4+
5+
Write a program to find maximum sum rectangle in give 2D matrix. Assume there is at least one positive number in the 2D
6+
matrix.
7+
8+
Solution:
9+
--------
10+
11+
* Keep temp array with size as number of rows. Start left and right from 0 and keep adding values for each row and
12+
maintain them in this temp array.
13+
* Run Kadane's algorithm to find max sum subarray in temp. Now increment right by 1.
14+
* When right reaches last column reset right to 1 and left to 1.
15+
16+
Analysis
17+
--------
18+
* Space complexity of this algorithm is O(row)
19+
* Time complexity of this algorithm is O(row*col*col)
20+
21+
Video
22+
-----
23+
* https://youtu.be/yCQN096CwWM
24+
25+
References
26+
----------
27+
* http://www.geeksforgeeks.org/dynamic-programming-set-27-max-sum-rectangle-in-a-2d-matrix/
28+
"""
29+
30+
from collections import namedtuple
31+
32+
Result = namedtuple("Result","maxSum leftBound rightBound upBound lowBound")
33+
34+
KadanesResult = namedtuple("KadanesResult","maxSum start end")
35+
36+
37+
def kadanes(temp):
38+
max = 0
39+
maxStart = -1
40+
maxEnd = -1
41+
currentStart = 0
42+
maxSoFar = 0
43+
44+
for i in range(0, len(temp)):
45+
maxSoFar += temp[i]
46+
47+
if maxSoFar < 0:
48+
maxSoFar = 0
49+
currentStart = i + 1
50+
51+
if maxSoFar > max:
52+
maxStart = currentStart
53+
maxEnd = i
54+
max = maxSoFar
55+
56+
return KadanesResult(max, maxStart, maxEnd)
57+
58+
59+
def max_sub_sub_rectangle(rectangle):
60+
61+
rows = len(rectangle)
62+
cols = len(rectangle[0])
63+
64+
result = Result(float("-inf"), -1, -1, -1, -1)
65+
66+
for left in range(cols):
67+
temp = [0 for _ in range(rows)]
68+
for right in range(left, cols):
69+
for i in range(rows):
70+
temp[i] += rectangle[i][right]
71+
72+
kadanes_result = kadanes(temp)
73+
if kadanes_result.maxSum > result.maxSum:
74+
result = Result(kadanes_result.maxSum, left, right, kadanes_result.start, kadanes_result.end)
75+
76+
return result
77+
78+
if __name__ == '__main__':
79+
rectangle = [[2, 1, -3, -4, 5],
80+
[0, 6, 3, 4, 1],
81+
[2, -2, -1, 4, -5],
82+
[-3, 3, 1, 0, 3]]
83+
84+
result = max_sub_sub_rectangle(rectangle)
85+
assert 18 == result.maxSum
86+
print result

0 commit comments

Comments
 (0)