leetcode53 Maximum Subarray

 1 """
 2 Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
 3 Example:
 4 Input: [-2,1,-3,4,-1,2,1,-5,4],
 5 Output: 6
 6 Explanation: [4,-1,2,1] has the largest sum = 6.
 7 """
 8 """
 9 最开始的想法复杂了:建一个n*n的二维数组,存储[i,j]的和
10 因为最后的output只要和的值,不需要求是哪些序列,所以此想法
11 实现起来麻烦,效率还低
12 """
13 """
14 正确的算法应为:贪心算法
15 subMaxSum = max(nums[i]+nums[i-1], nums[i])
16 nums[i] = subMaxSum
17 保证num[i]存的是i之前最大的和
18 """
19 
20 class Solution:
21     def maxSubArray(self, nums):
22         length = len(nums)
23         for i in range(1, length):
24             #当前值的大小与前面的值之和比较,若当前值更大,则取当前值,舍弃前面的值之和
25             subMaxSum = max(nums[i]+nums[i-1], nums[i])
26             nums[i] = subMaxSum#将当前和最大的赋给nums[i],新的nums存储的为和值
27         return max(nums)

 

posted @ 2020-02-11 23:08  yawenw  阅读(93)  评论(0编辑  收藏  举报