# -*- coding:utf-8 -*-
class Solution:
def FindGreatestSumOfSubArray(self, array):
# write code here
m = len(array)
dp = [0 for _ in range(m)]
dp[0] = array[0]
res = float("-inf")
for i in range(1, m):
dp[i] = max(0, dp[i-1]) + array[i]
res = max(dp[i], res)
return res
扩展成2维的
class Solution:
def FindGreatestSumOfSubArray(self, array):
# write code here
m = len(array)
dp = [0 for _ in range(m)]
dp[0] = array[0]
res = float("-inf")
for i in range(1, m):
dp[i] = max(0, dp[i-1]) + array[i]
res = max(dp[i], res)
return res
def FindGreatestSumOfSubArray2(self, array):
m, n = len(array), len(array[0])
res = float("-inf")
temp = [0 for _ in range(n)]
for i in range(m):
for j in range(i, m): #确定上下边界,找最大子矩阵,转化成1维的问题
for k in range(n):
if i == j:
temp[k] = 0
temp[k] += array[j][k]
print(i, j, temp)
res = max(res, self.FindGreatestSumOfSubArray(temp))
return res
if __name__ == "__main__":
A = [[1, 5, -3, 6, -7], [3, 5, -9, -4, 6], [-8, 4, 0, 12, -3], [3, -1, 5, -5, 8]]
s = Solution()
print(s.FindGreatestSumOfSubArray2(A))
网友评论