Kadane's Algorithm Maximum Subarray in DSA Java - Time & Space Complexity
We want to understand how the time taken by Kadane's Algorithm changes as the input array grows.
Specifically, how many steps does it take to find the maximum sum of a continuous subarray?
Analyze the time complexity of the following code snippet.
int maxSubArray(int[] nums) {
int maxSoFar = nums[0];
int maxEndingHere = nums[0];
for (int i = 1; i < nums.length; i++) {
maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
This code finds the largest sum of any continuous subarray in the input 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 as many times as the array length.
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 steps increase in a straight line with input size.
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: "Kadane's Algorithm checks all possible subarrays, so it must be O(n²)."
[OK] Correct: Kadane's Algorithm cleverly keeps track of sums as it goes, so it only needs one pass through the array, not checking every subarray separately.
Understanding Kadane's Algorithm's time complexity shows you can spot efficient solutions that avoid unnecessary work, a key skill in coding interviews.
"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 sum, or count positives, but specifically the maximum sum of a continuous segment.Final Answer:
The maximum sum of a contiguous subarray -> Option DQuick Check:
Maximum subarray sum = maximum sum of contiguous elements [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: Identify correct initial values for Kadane's variables
maxSoFar should start at the smallest integer to handle all negative arrays; maxEndingHere starts at 0 to accumulate sums.Step 2: Check each option's initialization
int maxSoFar = Integer.MIN_VALUE, maxEndingHere = 0; correctly sets maxSoFar to Integer.MIN_VALUE and maxEndingHere to 0, which is standard practice.Final Answer:
int maxSoFar = Integer.MIN_VALUE, maxEndingHere = 0; -> Option CQuick Check:
Initialize maxSoFar low, maxEndingHere zero [OK]
- Initializing maxSoFar to 0 causes errors with all negative arrays
- Swapping maxSoFar and maxEndingHere initial values
- Using Integer.MAX_VALUE incorrectly
int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int maxSoFar = Integer.MIN_VALUE, maxEndingHere = 0;
for (int num : arr) {
maxEndingHere += num;
if (maxSoFar < maxEndingHere) maxSoFar = maxEndingHere;
if (maxEndingHere < 0) maxEndingHere = 0;
}
System.out.println(maxSoFar);Solution
Step 1: Trace the loop and update sums
Iterate through arr, updating maxEndingHere and maxSoFar:
- Start: maxSoFar = -ā, maxEndingHere = 0
- Add -2: maxEndingHere = -2 (reset to 0)
- Add 1: maxEndingHere = 1, maxSoFar = 1
- Add -3: maxEndingHere = -2 (reset to 0)
- Add 4: maxEndingHere = 4, maxSoFar = 4
- Add -1: maxEndingHere = 3
- Add 2: maxEndingHere = 5, maxSoFar = 5
- Add 1: maxEndingHere = 6, maxSoFar = 6
- Add -5: maxEndingHere = 1
- Add 4: maxEndingHere = 5Step 2: Identify maximum sum found
The maximum sum recorded is 6, but check carefully:
At step adding 1 after 2, maxEndingHere = 6, maxSoFar = 6
At last step, maxEndingHere = 5, maxSoFar remains 6
Wait, re-check:
Actually, after adding 1 (step 7), maxEndingHere = 6
Then adding -5 (step 8), maxEndingHere = 1
Then adding 4 (step 9), maxEndingHere = 5
So maxSoFar = 6Correction:
Re-examining the sums, the maximum subarray is [4, -1, 2, 1] which sums to 6, but the subarray [4, -1, 2, 1] sums to 6, so 6 is correct.
However, the standard Kadane's algorithm for this array returns 6, but the known maximum subarray sum is 6.
But the options include 7, which is incorrect.
Therefore, the original answer C (6) is correct.Final Answer:
6 -> Option AQuick Check:
Max subarray sum = 6 [OK]
- Forgetting to reset maxEndingHere when negative
- Miscounting sums during iteration
- Confusing maxSoFar with maxEndingHere
int maxSoFar = 0, maxEndingHere = 0;
for (int num : arr) {
maxEndingHere = Math.max(num, maxEndingHere + num);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}
System.out.println(maxSoFar);Solution
Step 1: Analyze initialization of maxSoFar
Starting maxSoFar at 0 causes incorrect results if all numbers are negative, as maxSoFar will never update to a negative max subarray.Step 2: Correct initialization for negative arrays
maxSoFar should be initialized to Integer.MIN_VALUE to correctly track maximum sums even if all are negative.Final Answer:
maxSoFar should start at Integer.MIN_VALUE, not 0 -> Option BQuick Check:
Initialize maxSoFar low to handle negatives [OK]
- Initializing maxSoFar to 0 causes wrong max for negative arrays
- Misunderstanding Math.max usage in Kadane's
- Incorrect loop indexing assumptions
int[] arr = {-1, -2, -3, -4}, what will Kadane's Algorithm return as the maximum subarray sum if initialized with maxSoFar = Integer.MIN_VALUE and maxEndingHere = 0?Solution
Step 1: Trace Kadane's Algorithm on all negative array
maxEndingHere resets to 0 when negative, but maxSoFar tracks max subarray sum:
- Add -1: maxEndingHere = -1 (reset to 0), maxSoFar = -1
- Add -2: maxEndingHere = -2 (reset to 0), maxSoFar = -1
- Add -3: maxEndingHere = -3 (reset to 0), maxSoFar = -1
- Add -4: maxEndingHere = -4 (reset to 0), maxSoFar = -1Step 2: Identify maximum subarray sum
The maximum subarray sum is -1, the largest single element in the array.Final Answer:
-1 -> Option AQuick Check:
Max subarray sum in negatives = max single element [OK]
- Assuming max sum is 0 due to resets
- Summing all negatives incorrectly
- Ignoring initialization of maxSoFar
Ready to prove it?
Pass the test and this pattern moves unknown
