[LeetCode] 53. Maximum Subarray_Easy tag: Dynamic Programming

时间:2023-12-11 17:01:02

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. 这个题目思路跟[LeetCode] 198. House Robber _Easy tag: Dynamic Programming很像, 我们只需要得到动态方程式, A[i] 是maxsum which contains nums[i] for sure,
then A[i] = max(A[i-1] + nums[i], nums[i]), init: A[0] = nums[0] 1. Constraints
1) size >= 1
2) elsement will be integer 2. Ideas Dynamic Programming T: O(n) S; O(1) using rolling array 3. Code
3.1) S: O(n)
class Solution:
def maxSum(self, nums):
n = len(nums)
dp = [] * n
dp[], ans = nums[], nums[]
for i in range(, n):
dp[i] = max(dp[i-] + nums[i], nums[i])
ans = max(ans, dp[i])
return ans

3.2)   S; O(1)   using rolling array

class Solution:
def maxSum(self, nums):
n = len(nums)
dp = []*
dp[], ans = nums[], nums[]
for i in range(, n):
dp[i%] = max(dp[i% -] + nums[i], nums[i])
ans = max(ans, dp[i%])
return ans

4. Test cases