LintCode: 最大子数组

容易 最大子数组 查看运行结果

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

您在真实的面试中是否遇到过这个题? Yes
样例
给出数组[−2,2,−3,4,−1,2,1,−5,3],符合要求的子数组为[4,−1,2,1],其最大和为6

注意
子数组最少包含一个数

挑战
要求时间复杂度为O(n)


/*
动态规划:
状态方程:
ans[0] = nums[0]
ans[i] = max{ans[i-1] + nums[i], nums[i]} (i>=1)
*/

class Solution:
    """ @param nums: A list of integers @return: An integer denote the sum of maximum subarray """
    def maxSubArray(self, nums):
        # write your code here
        ans = [0 for i in range(len(nums))]
        ans[0] = nums[0]
        for i in range(1, len(nums)):
            ans[i] = max(ans[i-1] + nums[i], nums[i])
        return max(ans)


你可能感兴趣的:(最大子数组,lintcode)