leetcode--Maximum Subarray
题目链接:https://leetcode.com/problems/maximum-subarray/
算法类型:动态规划
题目分析:最大序列和
代码实现:
1 class Solution(object): 2 def maxSubArray(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 nums_len = len(nums) 8 if nums_len == 1: 9 return nums[0] 10 mid_len = nums_len / 2 11 left_max = self.maxSubArray(nums[ : mid_len]) 12 right_max = self.maxSubArray(nums[mid_len : ]) 13 14 mid_max_1 = nums[mid_len] 15 temp = mid_max_1 16 for i in range(0, mid_len)[::-1]: 17 temp += nums[i] 18 mid_max_1 = max(temp, mid_max_1) 19 20 mid_max_2 = nums[mid_len] 21 temp = mid_max_2 22 for item in nums[ mid_len + 1 : ]: 23 temp += item 24 mid_max_2 = max(temp, mid_max_2) 25 26 mid_max = mid_max_1 + mid_max_2 - nums[mid_len] 27 28 return max(left_max, right_max, mid_max)