Bird
Raised Fist0
DSA Typescriptprogramming~10 mins

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

Choose your learning style10 modes available
Concept Flow - Kadane's Algorithm Maximum Subarray
Start with first element as current and max sum
↓
Iterate through array elements
↓
Update current sum: max(current sum + element, element)
↓
Update max sum if current sum is greater
↓
Repeat until end of array
↓
Return max sum found
Kadane's algorithm scans the array once, keeping track of the current subarray sum and the maximum sum found so far.
Execution Sample
DSA Typescript
function maxSubArray(nums: number[]): number {
  let currentSum = nums[0];
  let maxSum = nums[0];
  for (let i = 1; i < nums.length; i++) {
    currentSum = Math.max(nums[i], currentSum + nums[i]);
    maxSum = Math.max(maxSum, currentSum);
  }
  return maxSum;
}
This code finds the maximum sum of any continuous subarray in the input array.
Execution Table
StepIndexCurrent ElementCurrent Sum CalculationCurrent SumMax SumSubarray Visual
10−2Initialize currentSum = −2, maxSum = −2−2−2[-2]
211max(1, −2 + 1) = 111[1]
32−3max(−3, 1 + (−3)) = −2−21[1, −3]
434max(4, −2 + 4) = 444[4] (new subarray)
54−1max(−1, 4 + (−1)) = 334[4, −1]
652max(2, 3 + 2) = 555[4, −1, 2]
761max(1, 5 + 1) = 666[4, −1, 2, 1]
87−5max(−5, 6 + (−5)) = 116[4, −1, 2, 1, −5]
984max(4, 1 + 4) = 556[4, −1, 2, 1, −5, 4]
10EndN/AEnd of array reachedN/A6Maximum subarray sum is 6
💡 Reached end of array, maxSum = 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
currentSum−21−24356155
maxSum−2114456666
index012345678End
Key Moments - 3 Insights
Why do we compare current element with currentSum + element?
Because if adding the current element to the existing subarray sum is worse than starting fresh from the current element, we reset currentSum to the current element. This is shown in execution_table rows 2 and 4 where currentSum resets.
Why do we update maxSum after updating currentSum?
Because maxSum must always hold the highest subarray sum found so far. If currentSum is greater, maxSum updates. See execution_table rows 4, 6, and 7 where maxSum changes after currentSum updates.
What happens if all numbers are negative?
Kadane's algorithm still works by initializing currentSum and maxSum to the first element. It picks the largest single element as maxSum. This is visible at step 1 where both are −2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4. What is the currentSum and why?
AcurrentSum is −2 because we added −3 and 4
BcurrentSum is 4 because we started a new subarray at index 3
CcurrentSum is 1 because we kept previous sum
DcurrentSum is 0 because we reset after negative sum
💡 Hint
Check execution_table row 4 under 'Current Sum Calculation' and 'Current Sum'
At which step does maxSum first become greater than 1?
AStep 6
BStep 3
CStep 4
DStep 7
💡 Hint
Look at the 'Max Sum' column in execution_table rows 2 to 7
If the input array started with [5, -1, 2], how would currentSum change at step 2?
AcurrentSum would be max(-1, 5 + (-1)) = 4
BcurrentSum would be max(-1, -1) = -1
CcurrentSum would be max(2, 4 + 2) = 6
DcurrentSum would reset to 5
💡 Hint
Check how currentSum is updated using max between current element and currentSum + element
Concept Snapshot
Kadane's Algorithm finds the max sum of a continuous subarray.
Initialize currentSum and maxSum to first element.
Iterate through array, update currentSum = max(current element, currentSum + current element).
Update maxSum = max(maxSum, currentSum).
Return maxSum after full iteration.
Full Transcript
Kadane's Algorithm scans the array once, keeping track of the current subarray sum and the maximum sum found so far. It starts with the first element as both currentSum and maxSum. For each next element, it decides whether to add it to the current subarray or start fresh from that element. It updates maxSum if the currentSum is higher. This way, it finds the maximum sum of any continuous subarray efficiently in one pass.

Practice

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

Solution

  1. 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.
  2. Step 2: Differentiate from other array operations

    It does not find minimum elements, total sum, or count positives, but specifically the largest sum of a continuous segment.
  3. Final Answer:

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

    Maximum subarray sum = The maximum sum of a contiguous subarray [OK]
Hint: Kadane finds max sum in continuous parts of array [OK]
Common Mistakes:
  • Confusing max sum with total sum of array
  • Thinking it finds minimum values
  • Assuming it counts positive numbers
2. Which of the following is the correct initialization step in Kadane's Algorithm in TypeScript?
easy
A. let maxSoFar = Number.MIN_SAFE_INTEGER, maxEndingHere = 0;
B. let maxSoFar = [], maxEndingHere = [];
C. let maxSoFar = 0, maxEndingHere = 0;
D. let maxSoFar = null, maxEndingHere = null;

Solution

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

    We initialize maxSoFar to the smallest safe integer to handle arrays with negative numbers correctly, and maxEndingHere to 0.
  2. Step 2: Check each option's correctness

    let maxSoFar = Number.MIN_SAFE_INTEGER, maxEndingHere = 0; correctly uses Number.MIN_SAFE_INTEGER for maxSoFar and 0 for maxEndingHere. Other options use incorrect types or values.
  3. Final Answer:

    let maxSoFar = Number.MIN_SAFE_INTEGER, maxEndingHere = 0; -> Option A
  4. Quick Check:

    Initialization with min safe integer = let maxSoFar = Number.MIN_SAFE_INTEGER, maxEndingHere = 0; [OK]
Hint: Initialize maxSoFar with smallest integer to handle negatives [OK]
Common Mistakes:
  • Initializing maxSoFar to 0 causes wrong results with all negatives
  • Using arrays instead of numbers for maxSoFar
  • Setting variables to null instead of numbers
3. What is the output of the following TypeScript code using Kadane's Algorithm?
function maxSubArray(nums: number[]): number {
  let maxSoFar = Number.MIN_SAFE_INTEGER;
  let maxEndingHere = 0;
  for (const num of nums) {
    maxEndingHere = Math.max(num, maxEndingHere + num);
    maxSoFar = Math.max(maxSoFar, maxEndingHere);
  }
  return maxSoFar;
}

console.log(maxSubArray([-2,1,-3,4,-1,2,1,-5,4]));
medium
A. 6
B. 7
C. 5
D. 4

Solution

  1. Step 1: Trace the Kadane's Algorithm on the input array

    Iterate through [-2,1,-3,4,-1,2,1,-5,4]: max subarray sums update as -2,1, -2,4,3,5,6,1,5.
  2. Step 2: Identify the maximum sum found

    The maximum sum found during iteration is 6, which corresponds to subarray [4,-1,2,1].
  3. Final Answer:

    6 -> Option A
  4. Quick Check:

    Max subarray sum = 6 [OK]
Hint: Track maxEndingHere and maxSoFar updates carefully [OK]
Common Mistakes:
  • Adding all positive numbers only
  • Ignoring negative numbers impact
  • Confusing maxSoFar with maxEndingHere
4. Identify the bug in this Kadane's Algorithm implementation and select the fix:
function maxSubArray(nums: number[]): number {
  let maxSoFar = 0;
  let maxEndingHere = 0;
  for (const num of nums) {
    maxEndingHere = Math.max(num, maxEndingHere + num);
    maxSoFar = Math.max(maxSoFar, maxEndingHere);
  }
  return maxSoFar;
}
medium
A. Remove resetting maxEndingHere to 0 when negative
B. Initialize maxSoFar with Number.MIN_SAFE_INTEGER instead of 0
C. Change maxEndingHere += num to maxEndingHere = num
D. Return maxEndingHere instead of maxSoFar

Solution

  1. Step 1: Analyze initialization problem

    Initializing maxSoFar to 0 causes wrong results if all numbers are negative, as maxSoFar never updates below 0.
  2. Step 2: Fix initialization to handle negative arrays

    Setting maxSoFar to Number.MIN_SAFE_INTEGER allows correct tracking of max sums even if all are negative.
  3. Final Answer:

    Initialize maxSoFar with Number.MIN_SAFE_INTEGER instead of 0 -> Option B
  4. Quick Check:

    Proper initialization fixes negative-only arrays [OK]
Hint: Use smallest integer for maxSoFar to handle negatives [OK]
Common Mistakes:
  • Leaving maxSoFar as 0 causes wrong max for negatives
  • Removing reset of maxEndingHere breaks algorithm logic
  • Returning wrong variable from function
5. Given an array of integers, how can Kadane's Algorithm be adapted to also return the start and end indices of the maximum sum subarray?
Choose the correct approach.
hard
A. Use two nested loops to find max sum and indices
B. Store all subarrays and pick the max sum one at the end
C. Track start index when maxEndingHere resets; update end index when maxSoFar updates
D. Return the first positive element's index as start and end

Solution

  1. Step 1: Understand Kadane's Algorithm extension for indices

    When maxEndingHere resets to current element, update start index; when maxSoFar updates, update end index to current position.
  2. Step 2: Compare with other approaches

    Storing all subarrays or using nested loops is inefficient; returning first positive index is incorrect.
  3. Final Answer:

    Track start index when maxEndingHere resets; update end index when maxSoFar updates -> Option C
  4. Quick Check:

    Index tracking with resets and updates = Track start index when maxEndingHere resets; update end index when maxSoFar updates [OK]
Hint: Update start on reset, end on max update for indices [OK]
Common Mistakes:
  • Using nested loops loses Kadane's efficiency
  • Ignoring index updates when maxEndingHere resets
  • Assuming first positive element is max subarray start
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