What if you could find the best winning streak in your numbers instantly, without checking every possibility?
Why Kadane's Algorithm Maximum Subarray in DSA Typescript?
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 by hand would take forever!
Manually checking every possible continuous period means looking at many combinations. This is slow and tiring, especially if the list is long. You might also make mistakes adding or missing some periods.
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, saving time and avoiding errors.
let maxSum = -Infinity; for (let i = 0; i < arr.length; i++) { for (let j = i; j < arr.length; j++) { let sum = 0; for (let k = i; k <= j; k++) sum += arr[k]; if (sum > maxSum) maxSum = sum; } }
let maxSum = arr[0]; let currentSum = 0; for (const num of arr) { currentSum = Math.max(num, currentSum + num); maxSum = Math.max(maxSum, currentSum); }
This lets you instantly 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 identifying the period with the highest gain.
Manual checking of all subarrays is slow and error-prone.
Kadane's Algorithm finds the maximum sum subarray in one pass.
It helps quickly identify the best continuous segment in data.
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 largest sum of a continuous segment.Final Answer:
The maximum sum of a contiguous subarray -> Option DQuick Check:
Maximum subarray sum = The maximum sum of a contiguous subarray [OK]
- Confusing max sum with total sum of array
- Thinking it finds minimum values
- Assuming it counts positive numbers
Solution
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.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.Final Answer:
let maxSoFar = Number.MIN_SAFE_INTEGER, maxEndingHere = 0; -> Option AQuick Check:
Initialization with min safe integer = let maxSoFar = Number.MIN_SAFE_INTEGER, maxEndingHere = 0; [OK]
- Initializing maxSoFar to 0 causes wrong results with all negatives
- Using arrays instead of numbers for maxSoFar
- Setting variables to null instead of numbers
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]));Solution
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.Step 2: Identify the maximum sum found
The maximum sum found during iteration is 6, which corresponds to subarray [4,-1,2,1].Final Answer:
6 -> Option AQuick Check:
Max subarray sum = 6 [OK]
- Adding all positive numbers only
- Ignoring negative numbers impact
- Confusing maxSoFar with maxEndingHere
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;
}Solution
Step 1: Analyze initialization problem
Initializing maxSoFar to 0 causes wrong results if all numbers are negative, as maxSoFar never updates below 0.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.Final Answer:
Initialize maxSoFar with Number.MIN_SAFE_INTEGER instead of 0 -> Option BQuick Check:
Proper initialization fixes negative-only arrays [OK]
- Leaving maxSoFar as 0 causes wrong max for negatives
- Removing reset of maxEndingHere breaks algorithm logic
- Returning wrong variable from function
Choose the correct approach.
Solution
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.Step 2: Compare with other approaches
Storing all subarrays or using nested loops is inefficient; returning first positive index is incorrect.Final Answer:
Track start index when maxEndingHere resets; update end index when maxSoFar updates -> Option CQuick Check:
Index tracking with resets and updates = Track start index when maxEndingHere resets; update end index when maxSoFar updates [OK]
- Using nested loops loses Kadane's efficiency
- Ignoring index updates when maxEndingHere resets
- Assuming first positive element is max subarray start
Ready to prove it?
Pass the test and this pattern moves unknown
