[LeetCode]题解(python):053-Maximum Subarray


题目来源

https://leetcode.com/problems/maximum-subarray/

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.


题意分析


Input: a list

Output: a number

Conditions:求最大连续子序列的和


题目思路


这题有点像动态规划,但是发现不需要索引之类的,所以想直接知道以某个值为结尾的最大子串的和,用d[]来存储该和,然后遍历一次即可,注意用max值来保存所需,不断更新max值

做完之后发现其实没必要用一个数组保存所有的和,直接用另一个变量保存前一个位置的最大和即可,代码是用list保存的没有改进= =


AC代码(Python)


 1 __author__ = 'YE'
 2 
 3 class Solution(object):
 4     def maxSubArray(self, nums):
 5         """
 6         :type nums: List[int]
 7         :rtype: int
 8         """
 9         length = len(nums)
10         if length == 0:
11             return 0
12         if length == 1:
13             return nums[0]
14 
15         d = [0 for i in range(length)]
16 
17         d[0] = nums[0]
18         max = d[0]
19 
20         for i in range(1, length):
21             d[i] = nums[i] + d[i - 1] if (nums[i] + d[i - 1]) > nums[i] else nums[i]
22             if d[i] > max:
23                 max = d[i]
24 
25 
26         return max
27 
28 s = Solution()
29 nums = [-2,1,-3,4,-1,2,1,-5, 4]
30 print(s.maxSubArray(nums))

 

posted @ 2015-12-28 15:14  loadofleaf  Views(283)  Comments(0Edit  收藏  举报