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.

  1. Initialize maxGlobal and currentMax with the value of the first element.
  2. Iterate through the array starting from the second element:
    • For each number, your currentMax is either the number itself (starting fresh) OR the number added to your previous currentMax (maintaining momentum).
    • Update maxGlobal if currentMax reaches a new overall peak.
  3. Print the final maxGlobal value.

01EXAMPLE 1

Input[-2,1,-3,4,-1,2,1,-5,4]
Output6

Explanation: Subarray [4,-1,2,1] has sum 6.

Constraints

  • Solve in O(n) time.
ArraysAlgorithms
JavaScript
Loading...
1 Hidden

Input Arguments

nums[-2,1,-3,4,-1,2,1,-5,4]

Expected Output

6

Click RUN to test your solution