Link: https://leetcode.com/problems/maximum-subarray/
Solution:
Intuition
This problem is a classic application of kadanes greedy algorithm. Not really much to this problem if you understand how kadane’s works. The idea is that if the current subarray sum added to the next element is smaller than the next element, we can discard the current subarray sum because it cannot be part of the maximum subarray.
Its important to note that negative numbers can be part of the max subarray given that they connect positive sum subarrays together.
For example:
[1,2,3,4,-1,1,2,3,4]
-1 is part of the maximum subarray because it connects the subarrays [1,2,3,4] and [1,2,3,4] for a max subarray sum of 19
Implementation (DP table)
Implementation (Optimized DP)
Visual
Review 1
Classic Kadane’s algorithm. I prefer this implementation: