Solution: Maximum Subarray
Let's solve the Maximum Subarray problem.
We'll cover the following
Statement
Given an unsorted array nums
, find the sum of the maximum sum subarray. The maximum sum subarray is an array of contiguous elements in nums
for which the sum of the elements is maximum.
Constraints:
nums.length
nums[i]
Solution
The maximum subarray sum problem inherently involves examining various subarrays to check if their sum is maximized, and the most convenient and efficient way to do this is using dynamic programming. The key idea is to efficiently find the maximum subarray ending at any position based on the maximum subarray ending at the previous position.
In the context of this problem, we’ll use Kadane’s algorithm. It uses the bottom-up approach of dynamic programming to solve subproblems iteratively, starting from the smallest subproblems and building up toward the larger problem. The subproblem here is to find the maximum subarray sum that ends at a specific index i
. We need to calculate this for every index i
in the array. The base case is the first element of the array, where both the current subarray sum and maximum subarray sum are initialized with the first element’s value. This is the starting point for solving the subproblems. We reuse the previously computed maximum subarray sum at each step to find the solution for the current subproblem.
The steps of the algorithm are given below:
Initialize a
currMax
variable to keep track of the maximum sum of the current array index and anotherglobalMax
variable to keep track of the largest sum seen so far. Both variables will be initialized with the first element ofnums
.Traverse the array from the second element until the end of the array is reached.
While traversing, if
currMax
is less than 0, assign it the element at the current index. Otherwise, add the element at the current index tocurrMax
.Next, if
globalMax
is less thancurrMax
, reassign it tocurrMax
.
Let’s look at the illustration below to better understand the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.