Given an integer array nums, please find a continuous subarray with the maximum sum (the subarray contains at least one element), and return its maximum sum. A subarray is a contiguous part of an array.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The sum of consecutive subarrays [4,-1,2,1] is the largest, which is 6.
Example 2:
input: nums = [1]
output: 1
Example 3:
Input: nums = [5,4,-1,7,8]
Output: 23
Dynamic programming:
1. The subscript meaning of the dp array (dp table)
dp[i]: the sum of the largest continuous subsequences before the subscript i is dp[i].
2. The recursive formula
dp[i] can only be deduced in two directions:
dp[i - 1] + nums[i], that is: nums[i] joins the current continuous subsequence and
nums[i], that is: start from the beginning The calculation of the current continuous subsequence sum
must be the largest, so dp[i] = max(dp[i - 1] + nums[i], nums[i]); 3. The initialization of the
dp array
can be seen from the recursive formula: dp[i] is the state dependent on dp[i - 1], and dp[0] is the basis of the recursive formula. According to the definition of dp[i], dp[0] = nums[0].
4.
In the traversal order recursion formula, dp[i] depends on the state of dp[i - 1], and needs to be traversed from front to back.
def maxSubArray(nums):
dp = [0] * len(nums)
dp[0] = nums[0]
for i in range(1,len(nums)):
dp[i] = max(dp[i-1] + nums[i],nums[i])
return max(dp)
if __name__ == "__main__":
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(maxSubArray(nums))
def maxSubArray(nums):
pre,result = 0, nums[0]
for el in nums:
pre = max(pre + el,el)
result = max(result,pre)
return result