LeetCode 0053. Maximum Subarray largest sub-sequence and Easy [] [] [Dynamic Programming Python]
Problem
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
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.
problem
Given an array of integers nums
, and find a maximum sub-arrays having a continuous (subarray least one element), and to return to its maximum.
Example:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
Advanced:
If you have implemented a complexity of O (n) of the solution, try to solve a more sophisticated use of divide and conquer.
Thinking
Dynamic Programming
Find dp recurrence formula. dp equal to the number of each position together with the foregoing dp, dp is a current negative side do not add up.
Time complexity: O (len (the nums))
spatial complexity: O (. 1)
Python code
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