What if you could find the best earning streak in seconds, no matter how long the list is?
Why Kadane's Algorithm Maximum Subarray in DSA C++?
Imagine you have a list of daily profits and losses for your small business. You want to find the best continuous period where you made the most money. Doing this by checking every possible period manually would take forever!
Manually checking every possible continuous period means looking at all combinations, which grows very fast as the list gets longer. This is slow and easy to mess up, especially if the list is big.
Kadane's Algorithm quickly finds the best continuous period by keeping track of the current sum and the best sum found so far. It does this in just one pass through the list, making it fast and simple.
int maxSum = INT_MIN; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { int sum = 0; for (int k = i; k <= j; k++) sum += arr[k]; if (sum > maxSum) maxSum = sum; } }
int maxSum = arr[0], currentSum = 0; for (int i = 0; i < n; i++) { currentSum += arr[i]; if (currentSum > maxSum) maxSum = currentSum; if (currentSum < 0) currentSum = 0; }
This algorithm lets you quickly find the most profitable continuous period in any list of numbers, no matter how long.
Stock traders use this to find the best time to buy and sell stocks by looking at price changes over days to maximize profit.
Manual checking of all subarrays is slow and complex.
Kadane's Algorithm finds the maximum subarray sum in one pass.
It is efficient and easy to implement for large data.
Practice
Solution
Step 1: Understand the problem Kadane's Algorithm solves
Kadane's Algorithm is designed to find the maximum sum of a contiguous subarray within a one-dimensional array of numbers.Step 2: Compare options with the algorithm's purpose
Options A, B, and D do not describe the main goal of Kadane's Algorithm. Only The maximum sum of a contiguous subarray correctly states it finds the maximum sum of a contiguous subarray.Final Answer:
The maximum sum of a contiguous subarray -> Option DQuick Check:
Maximum subarray sum = maximum sum of contiguous elements [OK]
- Confusing maximum sum with maximum product
- Thinking it finds minimum element
- Assuming it sums all elements
Solution
Step 1: Understand variable roles in Kadane's Algorithm
max_so_far stores the maximum sum found so far, so it should start very low (INT_MIN) to allow any sum to replace it. max_ending_here tracks the current subarray sum and starts at 0.Step 2: Check each option's initialization
int max_so_far = INT_MIN, max_ending_here = 0; correctly initializes max_so_far to INT_MIN and max_ending_here to 0. Other options either start max_so_far at 0 or INT_MAX, which can cause incorrect results.Final Answer:
int max_so_far = INT_MIN, max_ending_here = 0; -> Option AQuick Check:
max_so_far = INT_MIN, max_ending_here = 0 [OK]
- Initializing max_so_far to 0 causes wrong results with negatives
- Setting max_ending_here to INT_MIN breaks logic
- Using INT_MAX causes overflow issues
int arr[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int n = 9;
int max_so_far = INT_MIN, max_ending_here = 0;
for (int i = 0; i < n; i++) {
max_ending_here += arr[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
std::cout << max_so_far << std::endl;Solution
Step 1: Trace Kadane's Algorithm on the array
Iterate through arr: max_ending_here and max_so_far update as follows:
- i=0: max_ending_here=-2, max_so_far=-2, reset max_ending_here=0
- i=1: max_ending_here=1, max_so_far=1
- i=2: max_ending_here=-2, max_so_far=1, reset max_ending_here=0
- i=3: max_ending_here=4, max_so_far=4
- i=4: max_ending_here=3, max_so_far=4
- i=5: max_ending_here=5, max_so_far=5
- i=6: max_ending_here=6, max_so_far=6
- i=7: max_ending_here=1, max_so_far=6
- i=8: max_ending_here=5, max_so_far=6Step 2: Identify maximum subarray sum
The maximum sum found is 6, which corresponds to subarray [4, -1, 2, 1].Final Answer:
6 -> Option AQuick Check:
Max subarray sum = 6 [OK]
- Not resetting max_ending_here when negative
- Confusing max_so_far with current sum
- Miscounting subarray sums
int maxSubArraySum(int arr[], int n) {
int max_so_far = 0, max_ending_here = 0;
for (int i = 0; i < n; i++) {
max_ending_here += arr[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}Solution
Step 1: Analyze initialization impact on negative arrays
Starting max_so_far at 0 causes incorrect results if all array elements are negative, as max_so_far will never update to a negative sum.Step 2: Fix initialization to handle all negative values
Setting max_so_far to INT_MIN allows it to update correctly even if all elements are negative, ensuring the maximum subarray sum is found.Final Answer:
Initialize max_so_far to INT_MIN instead of 0 -> Option CQuick Check:
max_so_far = INT_MIN fixes negative-only arrays [OK]
- Leaving max_so_far at 0 causes wrong max for negatives
- Removing reset breaks algorithm logic
- Changing loop start misses first element
int arr[] = {-8, -3, -6, -2, -5, -4}; What is the maximum subarray sum using Kadane's Algorithm?Solution
Step 1: Understand Kadane's behavior with all negative numbers
When all numbers are negative, resetting max_ending_here to 0 causes the algorithm to miss the largest (least negative) number. Proper initialization with max_so_far = INT_MIN helps track the max single element.Step 2: Identify the maximum single element
The largest number in the array is -2, which is the maximum subarray sum since any longer subarray sum will be smaller.Final Answer:
-2 -> Option BQuick Check:
Max single negative element = -2 [OK]
- Assuming max sum is 0 by resetting sums
- Ignoring single element max in negative arrays
- Confusing minimum with maximum
Ready to prove it?
Pass the test and this pattern moves unknown
