Bird
Raised Fist0
DSA Cprogramming~10 mins

Kadane's Algorithm Maximum Subarray in DSA C - Execution Trace

Choose your learning style10 modes available
Concept Flow - Kadane's Algorithm Maximum Subarray
Start with first element
↓
Initialize current_sum and max_sum
↓
For each next element
↓
Update current_sum = max(element, current_sum + element)
↓
Update max_sum = max(max_sum, current_sum)
↓
Repeat until end of array
↓
Return max_sum
Kadane's algorithm scans the array once, keeping track of the best sum ending at each position and the overall best sum found.
Execution Sample
DSA C
int maxSubArray(int* nums, int numsSize) {
    int current_sum = nums[0];
    int max_sum = nums[0];
    for (int i = 1; i < numsSize; i++) {
        current_sum = (nums[i] > current_sum + nums[i]) ? nums[i] : current_sum + nums[i];
        max_sum = (max_sum > current_sum) ? max_sum : current_sum;
    }
    return max_sum;
}
This code finds the maximum sum of any contiguous subarray in the input array.
Execution Table
StepOperationIndex iCurrent Element nums[i]Current SumMax SumSubarray Considered
1Initialize0-2-2-2[-2]
2Compare nums[1] and current_sum + nums[1]11max(1, -2+1)=1max(-2,1)=1[1]
3Compare nums[2] and current_sum + nums[2]2-3max(-3,1-3)=-2max(1,-2)=1[1,-3]
4Compare nums[3] and current_sum + nums[3]34max(4,-2+4)=4max(1,4)=4[4]
5Compare nums[4] and current_sum + nums[4]4-1max(-1,4-1)=3max(4,3)=4[4,-1]
6Compare nums[5] and current_sum + nums[5]52max(2,3+2)=5max(4,5)=5[4,-1,2]
7Compare nums[6] and current_sum + nums[6]61max(1,5+1)=6max(5,6)=6[4,-1,2,1]
8Compare nums[7] and current_sum + nums[7]7-5max(-5,6-5)=1max(6,1)=6[4,-1,2,1,-5]
9Compare nums[8] and current_sum + nums[8]84max(4,1+4)=5max(6,5)=6[4,-1,2,1,-5,4]
10End of array---6Maximum subarray sum found
💡 Reached end of array, max_sum = 6 is the maximum subarray sum
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5After Step 6After Step 7After Step 8After Step 9Final
current_sum-21-24356155
max_sum-2114456666
i012345678-
Key Moments - 3 Insights
Why do we compare nums[i] with current_sum + nums[i] instead of just adding?
Because if current_sum + nums[i] is less than nums[i], starting fresh at nums[i] gives a better sum. See execution_table steps 2 and 4 where current_sum resets.
Why do we update max_sum after updating current_sum?
Because max_sum must always hold the best sum found so far, including the new current_sum. See execution_table steps 4 and 7 where max_sum updates after current_sum.
What happens if all numbers are negative?
Kadane's algorithm still works because it initializes current_sum and max_sum with the first element. The max_sum will be the largest (least negative) number. See step 1 initialization.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4. What is the current_sum value?
A4
B-2
C1
D3
💡 Hint
Check the 'Current Sum' column at step 4 in execution_table.
At which step does max_sum first become 5?
AStep 5
BStep 6
CStep 7
DStep 8
💡 Hint
Look at the 'Max Sum' column in execution_table and find when it changes to 5.
If the input array started with a large positive number instead of -2, how would current_sum change at step 1?
AIt would be that large positive number
BIt would remain -2
CIt would be zero
DIt would be the sum of first two elements
💡 Hint
current_sum initializes to nums[0], see variable_tracker 'Start' value.
Concept Snapshot
Kadane's Algorithm finds the maximum sum of a contiguous subarray.
Initialize current_sum and max_sum with first element.
For each element, update current_sum = max(element, current_sum + element).
Update max_sum = max(max_sum, current_sum).
Return max_sum after processing all elements.
Full Transcript
Kadane's Algorithm scans the array once to find the maximum sum of any contiguous subarray. It starts by setting current_sum and max_sum to the first element. Then, for each next element, it decides whether to add it to the current_sum or start fresh from that element, whichever is larger. After updating current_sum, it updates max_sum if current_sum is greater. This process continues until the end of the array, and max_sum holds the maximum subarray sum. The execution table shows each step with current_sum and max_sum values, and the variable tracker records their changes. Key moments clarify why comparisons are made and how the algorithm handles negative numbers. The visual quiz tests understanding of these steps.

Practice

(1/5)
1. What does Kadane's Algorithm primarily help to find in an array?
easy
A. The total sum of all elements
B. The minimum element in the array
C. The maximum sum of a contiguous subarray
D. The maximum product of any two elements

Solution

  1. 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.
  2. Step 2: Compare with other options

    Options B, C, and D describe different problems unrelated to Kadane's Algorithm.
  3. Final Answer:

    The maximum sum of a contiguous subarray -> Option C
  4. Quick Check:

    Maximum subarray sum = maximum sum of contiguous elements [OK]
Hint: Kadane finds max sum in continuous parts of array [OK]
Common Mistakes:
  • Confusing max sum with max product
  • Thinking it finds minimum element
  • Assuming it sums all elements
2. Which of the following is the correct initialization step in Kadane's Algorithm in C?
easy
A. int max_so_far = INT_MIN, max_ending_here = 0;
B. int max_so_far = 0, max_ending_here = 0;
C. int max_so_far = 0, max_ending_here = INT_MIN;
D. int max_so_far = NULL, max_ending_here = 0;

Solution

  1. Step 1: Understand initialization in Kadane's Algorithm

    We initialize max_so_far to the smallest integer (INT_MIN) to handle arrays with all negative numbers correctly, and max_ending_here to 0 to start accumulating sums.
  2. Step 2: Evaluate each option

    int max_so_far = 0, max_ending_here = 0; initializes max_so_far to 0, which fails for all negative arrays. int max_so_far = 0, max_ending_here = INT_MIN; incorrectly initializes max_ending_here to INT_MIN. int max_so_far = NULL, max_ending_here = 0; uses NULL which is invalid for int.
  3. Final Answer:

    int max_so_far = INT_MIN, max_ending_here = 0; -> Option A
  4. Quick Check:

    Use INT_MIN for max_so_far to handle negatives [OK]
Hint: Start max_so_far at INT_MIN to handle negatives [OK]
Common Mistakes:
  • Initializing max_so_far to 0 causes wrong results
  • Using NULL for integer variables
  • Swapping initial values of variables
3. What is the output of the following C code using Kadane's Algorithm?
int arr[] = {-2, 3, 2, -1};
int n = 4;
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;
}
printf("%d", max_so_far);
medium
A. 4
B. 5
C. 3
D. -1

Solution

  1. Step 1: Trace the loop and update sums

    Iteration 0: max_ending_here = 0 + (-2) = -2; max_so_far = max(INT_MIN, -2) = -2; max_ending_here < 0, reset to 0.
    Iteration 1: max_ending_here = 0 + 3 = 3; max_so_far = max(-2, 3) = 3; max_ending_here >= 0, no reset.
    Iteration 2: max_ending_here = 3 + 2 = 5; max_so_far = max(3, 5) = 5; max_ending_here >= 0, no reset.
    Iteration 3: max_ending_here = 5 + (-1) = 4; max_so_far = max(5, 4) = 5; max_ending_here >= 0, no reset.
  2. Step 2: Final max_so_far value

    After loop ends, max_so_far is 5, which is the maximum subarray sum.
  3. Final Answer:

    5 -> Option B
  4. Quick Check:

    Max subarray sum = 5 [OK]
Hint: Add elements, reset sum if negative, track max sum [OK]
Common Mistakes:
  • Not resetting max_ending_here when negative
  • Confusing max_so_far with current sum
  • Incorrectly summing non-contiguous elements
4. Identify the bug in this Kadane's Algorithm implementation in C:
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;
}
medium
A. max_so_far should be initialized to INT_MIN
B. max_ending_here should be initialized to INT_MIN
C. Loop should start from i = 1
D. Return statement should return max_ending_here

Solution

  1. Step 1: Analyze initialization of max_so_far

    Initializing max_so_far to 0 fails when all array elements are negative, as max_so_far will never update to a negative number.
  2. Step 2: Correct initialization and effect

    Setting max_so_far to INT_MIN ensures the algorithm correctly finds the maximum subarray sum even if all numbers are negative.
  3. Final Answer:

    max_so_far should be initialized to INT_MIN -> Option A
  4. Quick Check:

    Use INT_MIN for max_so_far to handle negative arrays [OK]
Hint: Initialize max_so_far to INT_MIN for negative arrays [OK]
Common Mistakes:
  • Initializing max_so_far to 0 causes wrong max for negatives
  • Changing loop start index unnecessarily
  • Returning wrong variable
5. Given an array int arr[] = {-3, -2, -1, -4}, what is the maximum subarray sum using Kadane's Algorithm?
hard
A. -3
B. 0
C. -10
D. -1

Solution

  1. Step 1: Understand Kadane's behavior with all negative numbers

    When all numbers are negative, resetting max_ending_here to 0 loses the maximum negative number. Proper Kadane's initialization with max_so_far = INT_MIN helps track the largest negative number.
  2. Step 2: Trace the array values

    max_so_far starts at INT_MIN.
    i=0: max_ending_here = -3; max_so_far = -3; reset max_ending_here to 0 since negative.
    i=1: max_ending_here = -2; max_so_far = max(-3, -2) = -2; reset max_ending_here to 0.
    i=2: max_ending_here = -1; max_so_far = max(-2, -1) = -1; reset max_ending_here to 0.
    i=3: max_ending_here = -4; max_so_far = max(-1, -4) = -1; reset max_ending_here to 0.
  3. Final Answer:

    -1 -> Option D
  4. Quick Check:

    Max negative number = -1 [OK]
Hint: Max subarray in negatives is max single element [OK]
Common Mistakes:
  • Returning 0 instead of max negative
  • Not handling all negative arrays
  • Assuming sum must be positive
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard