Kadane’s Algorithm is an efficient algorithm for finding the maximum sum of a contiguous subarray within a one-dimensional numerical array. It operates in time, making it one of the most optimal solutions for this problem.
Key takeaways:
Kadane’s algorithm for maximum subarray sum: This problem is efficiently solved using Kadaness Algorithm with time complexity of
, making it suitable for large input arrays. Dynamic subarray management: The algorithm dynamically keeps track of the maximum subarray sum as it iterates through the array, updating the result when a higher sum is found.
Optimal for handling mixed positive and negative numbers: Kadane’s Algorithm is designed to handle arrays with both positive and negative numbers, ensuring the maximum sum subarray is identified even when negative values are present.
Frequently asked in coding interviews: Problems involving finding the maximum subarray sum are common in technical interviews at top tech companies like Google, Microsoft, and Facebook.
Real-world applications: This algorithm has applications in areas like stock market analysis, weather prediction, and any scenario where finding the maximum sum of consecutive elements is important.
Algorithmic efficiency: Kadane’s Algorithm is an optimal, linear-time solution, demonstrating the importance of efficiency in solving real-world problems.
The maximum subarray sum is the largest possible sum of a contiguous subarray within a given array. The subarray can consist of any number of consecutive elements, and the goal is to find the subarray that yields the highest sum.
Given an array of integers, nums
, find the sum of a
Let’s understand this with the help of an example array [-3, 1, -2, 5, 0, 3, 2, -4, 6]
. Out of all the possible subarrays, the subarray, [5, 0, 3, 2, -4, 6]
, produces a maximum sum of 12
, so the output of this input will be 12
.
Constraints:
nums.length
nums[i]
Let’s take a moment to ensure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem.
Maximum subarray sum
What is the output if the following array is given as input to the greedy approach for finding the maximum subarray sum?
nums = [1, 2, 2, 3, 3, 1, 4]
12
8
7
9
The maximum subarray sum problem can be efficiently solved using Kadane’s algorithm, a greedy approach that simplifies the decision-making process for finding the maximum sum of a contiguous subarray. The idea behind this approach is to iteratively decide whether to continue adding the current element to the existing subarray or start a new subarray. This decision is based on whether the current sum would be better by adding the current element or resetting the sum to just the current element itself.
In Kadane’s algorithm, we maintain two variables: the current subarray sum and the global maximum sum encountered so far. Starting from the first element, we check if adding the current element to the existing sum will increase it. If adding it makes the sum smaller, we reset the current sum to just the current element, effectively starting a new subarray. We continuously update the global maximum sum if the current sum exceeds it.
Here’s the detailed algorithm for the approach we just discussed:
Initialization:
We initialize a varaible curr_max
to the first element of the array, representing the current subarray sum.
We’ll also initalize global_max
to point the first element, representing the highest subarray sum encountered so far.
Iterating through the array:
We’ll traverse from the second element (index 1) and process each element:
If curr_max
becomes negative, we reset it to the current element, starting a new subarray.
Otherwise, we add the current element to curr_max
, extending the current subarray.
After updating curr_max
, we’ll compare it with global_max
. If curr_max
exceeds global_max
, the global maximum is updated.
Return the result:
Once the loop finishes, we return global_max
, which holds the maximum sum of any contiguous subarray.
Let’s look at the illustration below to better understand the solution:
Let’s look at the Python code for this solution below:
def find_max_sum_sublist(nums):if len(nums) < 1:return 0# Initialize the current subarray sum and the global maximum sumcurr_max = nums[0]global_max = nums[0]# Iterate through the array starting from the second elementfor i in range(1, len(nums)):# If the current subarray sum becomes negative, start a new subarrayif curr_max < 0:curr_max = nums[i] # Reset the current subarray sum to the current elementelse:curr_max += nums[i] # Otherwise, extend the current subarray sum# Update the global maximum sum if the current subarray sum is largerif global_max < curr_max:global_max = curr_max # Update global max with the larger sumreturn global_max # Return the maximum subarray sum founddef main():inputs = [[1, -2, 3, 4, -1, 2, 1, -5, 4],[-2, -3, -4, -1, -2],[5, 4, 3, 2, 1],[-3, -1, -1, -2, -2, 1, 3],[10, -5, 2, 3, -1, -2, 6],[1]]for i in range(len(inputs)):print(i + 1, ".\tInput array: ", inputs[i], sep="")print("\tMaximum subbary sum: ", find_max_sum_sublist(inputs[i]), sep="")print("-" * 100)if __name__ == "__main__":main()
Time complexity: Since we are only looping through the array once, the algorithm’s time complexity is
Space complexity: The space complexity of this algorithm is currentSum
and maximumSum
).
The greedy strategy ensures that negative subarrays are ignored early, allowing the algorithm to focus on positive-sum subarrays.
The running total (currentSum
) and a comparison with the global maximum (maximumSum
) guarantee the largest sum is found.
To learn more about data structures and algorithms and practice more LeetCode-based problems. Look at the following list of curated courses at Educative:
Haven’t found what you were looking for? Contact Us