Largest Contiguous Subarray

Leetcode link:


Given a list of integers, find the continguous subarray which gives the largest sum of the integers and return the sum.


Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.


To find the largest sum of the contiguous subarray, we can use Kadane's algorithm. The algorithm looks like this:

def maxSubArray(self, nums: List[int]) -> int:
max_curr, max_global = nums[0], nums[0]
for i in range(1, len(nums)):
max_curr = max(nums[i], max_curr + nums[i])
if max_curr > max_global:
max_global = max_curr
return max_global

To understand why Kadane's algorithm works, check out this video: