The Maximum Subarray Sum problem is a classic problem in computer science and programming interviews. It asks us to find the contiguous subarray within a one-dimensional array of numbers, which has the largest sum.
Given an integer array nums
, we want to find the contiguous subarray (containing at least one number) which has the largest sum and return that sum.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The subarray [4,-1,2,1] has the largest sum = 6.
Example 2:
Input: nums = [1]
Output: 1
Explanation: The subarray [1] has the largest sum = 1.
Before diving into a more efficient solution, let's first consider a naive approach for solving this problem. This approach involves checking every possible subarray, calculating the sum for each, and keeping track of the maximum sum found.
Here's a brief pseudocode of this naive solution:
def max_subarray_sum(nums): max_sum = float('-inf') for i in range(len(nums)): for j in range(i, len(nums)): current_sum = sum(nums[i:j + 1]) max_sum = max(max_sum, current_sum) return max_sum
While this method works, its time complexity is O(n^2), which can be inefficient for large datasets.
To optimize our approach, we can use Kadane's Algorithm, which efficiently determines the maximum subarray sum in linear time O(n).
Concept: The key idea behind Kadane's Algorithm is to maintain two variables:
current_sum
: This tracks the current subarray sum.max_sum
: This keeps a record of the maximum sum encountered so far.current_sum
by adding the current element.current_sum
becomes greater than max_sum
, update max_sum
.current_sum
drops below zero, reset it to zero. This is because any negative running sum will not contribute positively to future sums.Pseudocode:
def max_subarray_sum(nums): max_sum = float('-inf') current_sum = 0 for num in nums: current_sum += num max_sum = max(max_sum, current_sum) if current_sum < 0: current_sum = 0 return max_sum
Example Walkthrough:
Let's consider the example nums = [-2,1,-3,4,-1,2,1,-5,4]
and run through Kadane’s Algorithm:
max_sum
to -∞ and current_sum
to 0.current_sum = -2
, max_sum = -2
.current_sum = -1
, max_sum = -1
.current_sum = -4
, reset to 0.current_sum = 4
, max_sum = 4
.current_sum = 3
, max_sum = 4
.current_sum = 5
, max_sum = 5
.current_sum = 6
, max_sum = 6
.current_sum = 1
, max_sum = 6
.current_sum = 5
, max_sum = 6
.At the end, we output 6
as the maximum subarray sum, confirming that the subarray [4, -1, 2, 1]
indeed yields the highest sum.
By understanding and implementing Kadane’s Algorithm, anyone can tackle the Maximum Subarray Sum problem with ease, making it a valuable tool in your coding toolkit. Happy coding!
23/09/2024 | DSA
13/10/2024 | DSA
15/11/2024 | DSA
08/12/2024 | DSA
15/11/2024 | DSA
16/11/2024 | DSA
08/12/2024 | DSA
15/11/2024 | DSA
13/10/2024 | DSA
13/10/2024 | DSA
06/12/2024 | DSA