DP way (space O(N)): key point here is keep recording local max subarray sum while updating global max subarray sum
class Solution:
def maxSubArray(self, A: List[int]) -> int:
""" tc O(N) sc O(N)
dp[i]: max sub array sum ending with A[i]
use a global res to cache local subarary sum at each iteration
"""
n = len(A)
dp =[0]*n
dp[0] = A[0]
res = dp[0]
for i in range(1,n):
dp[i] = A[i] + (dp[i-1] if dp[i-1]> 0 else 0 )
res = max(res,dp[i])
return res
Kadane’s algo: main idea– if sum of subarray is positive, it’s possible to make next value bigger. So keep adding until subarray sum is negtive
class Solution:
def maxSubArray(self, A: List[int]) -> int:
""" tc O(N) sc O(1)
"""
n = len(A)
sums = A[0]
res = A[0]
for i in range(1,n):
if sums > 0:
sums += A[i]
else:
sums = A[i]
res = max(res,sums)
return res