一、题目描述
原文链接:https://leetcode.com/problems/maximum-subarray/description/
二、题目分析Given an integer array
nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.(给定整数数组nums,找到具有最大总和并返回其总和的连续子数组(包含至少一个数字)。)Example:
Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
动态规划,思路参考了http://blog.csdn.net/linhuanmars/article/details/21314059点击打开链接
三、代码实现
class Solution: def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ lsum=tsum= nums[0] #tsum为局部最大值(包含当前元素),lsum为全局最大值 for i in range(1,len(nums)): tsum = max(nums[i],tsum+nums[i]) lsum = max(tsum,lsum) return lsum