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.
- Calculate the sum of the very first
kelements to "prime" the window. - Slide the window one step at a time from index
kto the end. - In each step:
- Subtract the element that is leaving the window (
nums[i-k]). - Add the element that is entering the window (
nums[i]).
- Subtract the element that is leaving the window (
- Update your maximum sum if the new window total is higher.
- Print the final result.
01EXAMPLE 1
Input
nums=[2, 1, 5, 1, 3, 2], k=3Output
9Explanation: [5, 1, 3] sums to 9.
Constraints
- Solve in O(n) time.
ArraysSliding Window
JavaScriptSystem handles I/O — write your function only
Loading...
1 Hidden
Input Arguments
nums[2,1,5,1,3,2]
k3
Expected Output
9
Click RUN to test your solution