Maximum Sum Subarray (Fixed)

MediumAcc. 92.4%
+30 XP 12

The Signal Horizon (Sliding Window)

When processing live streams of data, we often care about the "current window" of information. Instead of starting from scratch every time the window moves, we use the Sliding Window technique: we subtract the data exiting the window and add the data entering it.

The Assignment

Your mission is to find the highest total in any contiguous window. Your function receives nums and a window size k.

  1. Calculate the sum of the very first k elements to "prime" the window.
  2. Slide the window one step at a time from index k to the end.
  3. In each step:
    • Subtract the element that is leaving the window (nums[i-k]).
    • Add the element that is entering the window (nums[i]).
  4. Update your maximum sum if the new window total is higher.
  5. Print the final result.

01EXAMPLE 1

Inputnums=[2, 1, 5, 1, 3, 2], k=3
Output9

Explanation: [5, 1, 3] sums to 9.

Constraints

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

Input Arguments

nums[2,1,5,1,3,2]
k3

Expected Output

9

Click RUN to test your solution