Problem
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Algorithm
Dynamic programming.
Code
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
if not nums:
return 0
n = len(nums)
ans = nums[0]
Sum = nums[0]
for i in range(1, n):
if Sum < 0:
Sum = 0
Sum += nums[i]
if ans < Sum:
ans = Sum
return ans