Kadane's Algorithm
HardAcc. 75.3%
+50 XP 25
The Maximum Momentum (Kadane's)
Imagine you are a treasure hunter walking through a canyon. Some areas have treasures (positive values) and some have traps (negative values). You want to find the continuous section of the canyon with the highest total treasure. If your "current momentum" becomes negative, it's better to abandon your current path and start fresh at the next point.
The Assignment
Your mission is to find the peak subarray sum. Your function receives an array nums.
- Initialize
maxGlobalandcurrentMaxwith the value of the first element. - Iterate through the array starting from the second element:
- For each number, your
currentMaxis either the number itself (starting fresh) OR the number added to your previouscurrentMax(maintaining momentum). - Update
maxGlobalifcurrentMaxreaches a new overall peak.
- For each number, your
- Print the final
maxGlobalvalue.
01EXAMPLE 1
Input
[-2,1,-3,4,-1,2,1,-5,4]Output
6Explanation: Subarray [4,-1,2,1] has sum 6.
Constraints
- Solve in O(n) time.
ArraysAlgorithms
JavaScriptSystem handles I/O — write your function only
Loading...
1 Hidden
Input Arguments
nums[-2,1,-3,4,-1,2,1,-5,4]
Expected Output
6
Click RUN to test your solution