美文网首页
【数组】连续子数组的最大和

【数组】连续子数组的最大和

作者: 一个想当大佬的菜鸡 | 来源:发表于2019-10-10 13:50 被阅读0次
    # -*- 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))
    

    相关文章

      网友评论

          本文标题:【数组】连续子数组的最大和

          本文链接:https://www.haomeiwen.com/subject/kwqzectx.html