41. 最大子数组

给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。

注意事项

子数组最少包含一个数
给出数组[−2,2,−3,4,−1,2,1,−5,3],符合要求的子数组为[4,−1,2,1],其最大和为6
2017.11.17

class Solution:
    """
    @param: nums: A list of integers
    @return: A integer indicate the sum of max subarray
    """
    def maxSubArray(self, nums):
        # write your code here
        temp = None
        max = None
        for i in nums:
            if temp == None:
                temp = i
            else:
                temp += i
            if max == None:
                max = temp
            if max <= temp:
                max = temp
            if temp <= 0:
                temp = 0
                #思路是,依次相加,如果加到出现负数或零,就放弃前面所有数
                #然后记录最大值
        return max

2017.11.20玩了几天

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容