Maximum Subarray
Array Math/Dynamic Programming
Problem
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
For example:
Thought Process
Kadane's Algorithm: The idea is we're going to look at each index and we're going to ask ourselves "What's the maximum subarray ending at this index."
It's a dynamic programming type problem where we need to identify the optimal substructure, which in this case is the maximum sum ending at that specific index (which will be the local sum). We then have to compare this local sum to the global sum.
Solution
Key Facts
The local maximum subarray is either the subarray at the current index OR the subarray of the current element combined with the previous maximum subarray. We can find the global max subarray from this.
Time Complexity
Time:
Space:
Last updated
Was this helpful?