Five minutes. One pattern. Stay fluent.

Daily etudes

Peak shift

Share task

Today’s task: “Peak shift”. Practice the Sliding window pattern! Given an integer array hours and an integer k, return the largest sum of any contiguous subarray containing exactly k elements. A contiguous... https://etuder.dev

Given an integer array hours and an integer k, return the largest sum of any contiguous subarray containing exactly k elements. A contiguous subarray consists of adjacent elements in their original order. The input satisfies 1 ≤ k ≤ len(hours). Values may be negative.

Example:

peak_shift([3, 1, 4, 1, 5], 3)  →  10

The three length-3 subarrays have sums 3+1+4=8, 1+4+1=6 and 4+1+5=10. The maximum is 10.

peak_shift([2, 2, 2], 1)  →  2

With k=1, each subarray has one element. Every candidate has sum 2.

Pattern: sliding_window - sum the first window, then add the next hour and drop the oldest