class Solution:
def maxSubArray(self, nums: List[int]) -> int:
n, maxSum, currSum = len(nums), nums[0], 0
for i in range(n):
currSum = max(0, currSum) + nums[i]
maxSum = max(currSum, maxSum)
return maxSum
Here is the more explainable version of Kadane's algorithm:
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
maxSub = nums[0]
curSum = 0
for i in nums:
if curSum < 0:
curSum = 0
curSum += i
maxSub = max(maxSub, curSum)
return maxSub
The logic is that whenever there is a negative prefix number, we flip the curSum back to 0 and continue incrementing whatever value we come across in the upcoming numbers to find the max sum of a contiguous subarray within the array.
Keep in mind that in this approach we completely disregard negative values so if for any reason there was a negative integer array it would mean that the max sum would only ever be 0.