Solution: Maximum Subarray
Let's solve the Maximum Subarray problem using the Dynamic Programming pattern.
We'll cover the following
Statement#
Given an integer array, nums, find the contiguous subarray that has the largest sum and return its sum.
Note: A subarray is a contiguous part of an array that contains at least one number.
Constraints:
-
nums.length -
nums[i]
Solution#
We’ll solve this problem using Kadane’s Algorithm. It’s a dynamic programming approach. The key idea is that we can efficiently find the maximum subarray ending at any position based on the maximum subarray ending at the previous position.
The subproblem here is finding 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 current subarray sum and maximum subarray sum are initialized with the first element’s value. This is the starting point for solving the subproblems. At each step, we reuse the previously computed maximum subarray sum to find the solution for the current subproblem.
The steps of the algorithm are given below:
-
Initialize two variables,
current_sumandmax_sum, with the value of the first element in the input list. These variables are used to keep track of the current sum of the subarray being considered, and the maximum sum found so far. -
Iterate through the input list, starting from the second element to the end of the list. Within the loop, perform the following steps:
-
If
current_sum + nums[i]is smaller thannums[i], this indicates that starting a new subarray withnums[i]would yield a larger sum than extending the previous subarray. In such cases, resetcurrent_sumtonums[i]. -
Compare the current
max_sumwith the updatedcurrent_sum. This step ensures that themax_sumalways stores the maximum sum encountered so far.
-
-
After the loop completes, the function returns the
max_sum, which represents the maximum sum of any contiguous subarray within the input list.
Let’s look at the following illustration to get a better understanding of the solution:
1 of 11
2 of 11
3 of 11
4 of 11
5 of 11
6 of 11
7 of 11
8 of 11
9 of 11
10 of 11
11 of 11
Let’s implement the algorithm as discussed above:
Time complexity#
The time complexity of this solution is , because we are iterating the array once, where is the total number of elements in the array.
Space complexity#
The space complexity of this solution is .
Maximum Subarray
Final Remarks