LeetCode 0053. Maximum Subarray最大子序和【Easy】【Python】【動態規劃】
LeetCodepython
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.git
Example:github
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.app
力扣ide
給定一個整數數組 nums
,找到一個具備最大和的連續子數組(子數組最少包含一個元素),返回其最大和。code
示例:leetcode
輸入: [-2,1,-3,4,-1,2,1,-5,4], 輸出: 6 解釋: 連續子數組 [4,-1,2,1] 的和最大,爲 6。
進階:get
若是你已經實現複雜度爲 O(n) 的解法,嘗試使用更爲精妙的分治法求解。it
動態規劃
找到 dp 遞推公式。dp 等於每一個位置的數字加上前面的 dp,當前面的 dp 是負數時就不要加了。
時間複雜度: O(len(nums))
空間複雜度: O(1)
class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 dp = 0 sum = -0xFFFFFFFF for i in range(len(nums)): dp = nums[i] + (dp if dp > 0 else 0) # if dp > 0: dp = nums[i] + dp, else: dp = nums[i] sum = max(sum, dp) return sum