Kadane's Algorithm Maximum Subarray in DSA C# - Time & Space Complexity
We want to understand how the time needed to find the maximum sum of a continuous subarray changes as the input array grows.
How does the algorithm's work increase when the array gets bigger?
Analyze the time complexity of the following code snippet.
int MaxSubArray(int[] nums) {
int maxSoFar = nums[0];
int currentMax = nums[0];
for (int i = 1; i < nums.Length; i++) {
currentMax = Math.Max(nums[i], currentMax + nums[i]);
maxSoFar = Math.Max(maxSoFar, currentMax);
}
return maxSoFar;
}
This code finds the largest sum of any continuous subarray inside the given array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single loop that goes through each element of the array once.
- How many times: Exactly once for each element, so n times if the array has n elements.
As the array gets bigger, the number of steps grows directly with the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The work grows in a straight line with input size; doubling the input doubles the work.
Time Complexity: O(n)
This means the time to find the maximum subarray sum grows directly with the size of the input array.
[X] Wrong: "Since we check sums of many subarrays, the time must be quadratic O(n²)."
[OK] Correct: Kadane's algorithm cleverly keeps track of sums as it goes, so it only needs one pass, not checking all subarrays separately.
Understanding Kadane's algorithm shows you can find efficient solutions by avoiding repeated work, a key skill in problem solving.
"What if we wanted to find the maximum subarray sum but also return the start and end indexes? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem Kadane's Algorithm solves
Kadane's Algorithm is designed to find the maximum sum of any contiguous subarray within a given array.Step 2: Differentiate from other array operations
It does not find minimum elements, total sums, or count positives, but specifically the largest sum of a continuous segment.Final Answer:
The maximum sum of a contiguous subarray -> Option BQuick Check:
Maximum subarray sum = The maximum sum of a contiguous subarray [OK]
- Confusing maximum subarray sum with total array sum
- Thinking it finds minimum or count of elements
- Assuming it works on non-contiguous elements
Solution
Step 1: Understand variable roles in Kadane's Algorithm
maxSoFar stores the maximum sum found so far, so it should start very low (int.MinValue) to handle negative arrays. maxEndingHere tracks current subarray sum and starts at 0.Step 2: Check each initialization
int maxSoFar = int.MinValue, maxEndingHere = 0; correctly initializes maxSoFar to int.MinValue and maxEndingHere to 0, allowing correct updates during iteration.Final Answer:
int maxSoFar = int.MinValue, maxEndingHere = 0; -> Option CQuick Check:
Initialize maxSoFar low, maxEndingHere zero [OK]
- Initializing maxSoFar to 0 causes wrong results with all negatives
- Setting maxEndingHere to int.MinValue breaks sum calculation
- Using int.MaxValue causes logic errors
int[] arr = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };
int maxSoFar = int.MinValue, maxEndingHere = 0;
foreach (int x in arr) {
maxEndingHere = Math.Max(x, maxEndingHere + x);
maxSoFar = Math.Max(maxSoFar, maxEndingHere);
}
Console.WriteLine(maxSoFar);Solution
Step 1: Trace Kadane's Algorithm on the array
Iterate and update maxEndingHere and maxSoFar:
- Start maxSoFar = -ā, maxEndingHere = 0
- x=-2: maxEndingHere=max(-2,0-2)=-2; maxSoFar=max(-ā,-2)=-2
- x=1: maxEndingHere=max(1,-2+1)=1; maxSoFar=max(-2,1)=1
- x=-3: maxEndingHere=max(-3,1-3)=-2; maxSoFar=1
- x=4: maxEndingHere=max(4,-2+4)=4; maxSoFar=4
- x=-1: maxEndingHere=max(-1,4-1)=3; maxSoFar=4
- x=2: maxEndingHere=max(2,3+2)=5; maxSoFar=5
- x=1: maxEndingHere=max(1,5+1)=6; maxSoFar=6
- x=-5: maxEndingHere=max(-5,6-5)=1; maxSoFar=6
- x=4: maxEndingHere=max(4,1+4)=5; maxSoFar=6Step 2: Identify the maximum sum found
The maximum sum found is 6, which corresponds to the subarray [4, -1, 2, 1].Final Answer:
6 -> Option AQuick Check:
Max subarray sum = 6 [OK]
- Adding all positive numbers incorrectly
- Not resetting maxEndingHere properly
- Confusing maxSoFar with last maxEndingHere
int maxSoFar = 0, maxEndingHere = 0;
foreach (int x in arr) {
maxEndingHere += x;
if (maxSoFar < maxEndingHere) maxSoFar = maxEndingHere;
if (maxEndingHere < 0) maxEndingHere = 0;
}
return maxSoFar;Solution
Step 1: Analyze initialization impact
Initializing maxSoFar to 0 causes wrong results if all numbers are negative, as maxSoFar will never be less than 0.Step 2: Correct initialization to handle negatives
Setting maxSoFar to int.MinValue allows the algorithm to correctly track maximum sums even if all elements are negative.Final Answer:
Initialize maxSoFar to int.MinValue instead of 0 -> Option DQuick Check:
Use int.MinValue for maxSoFar to handle negatives [OK]
- Leaving maxSoFar at 0 causes wrong max for negative arrays
- Removing reset breaks Kadane's logic
- Changing addition to assignment loses cumulative sum
Solution
Step 1: Understand Kadane's Algorithm extension
When maxEndingHere resets to current element, record that index as temporary start. When maxSoFar updates, update final start and end indices accordingly.Step 2: Avoid brute force methods
Storing all subarrays and using two nested loops are brute force and inefficient. Returning the first positive element's index as start and end is incorrect as max subarray may not start at first positive element.Final Answer:
Track temporary start index when maxEndingHere resets and update final start/end when maxSoFar changes -> Option AQuick Check:
Track indices on resets and max updates [OK]
- Using nested loops instead of Kadane's linear approach
- Ignoring index tracking during sum updates
- Assuming max subarray always starts at first positive
Ready to prove it?
Pass the test and this pattern moves unknown
