Created
February 19, 2015 07:23
-
-
Save m00nlight/34b0f6a2d6a26fcef930 to your computer and use it in GitHub Desktop.
Python max sub-array problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from operator import add, sub | |
import sys | |
def max_subarray(arr): | |
ret, cur = arr[0], 0 if arr[0] < 0 else arr[0] | |
for num in arr[1:]: | |
ret = max(ret, cur + num) | |
cur = max(0, cur + num) | |
return ret | |
def max_submatrix(matrix): | |
n = len(matrix) | |
sum_acc = [[0 for i in range(n)]] | |
ret = -128 | |
for row in matrix: | |
sum_acc.append(map(add, sum_acc[-1], row)) | |
for i in range(1, n + 1): | |
for j in range(i, n + 1): | |
tmp = map(sub, sum_acc[j], sum_acc[i - 1]) | |
ret = max(ret, max_subarray(tmp)) | |
return ret | |
if __name__ == '__main__': | |
n = sys.stdin.readline() | |
n = int(n) | |
matrix = [] | |
for i in range(n): | |
nums = sys.stdin.readline() | |
nums = map(lambda x: int(x), nums.split()) | |
matrix.append(nums) | |
print '%d\n' % (max_submatrix(matrix)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment