HardArraysNot started

Best revenue window

Given daily revenue in whole cents and a window width W, print the zero-based start index and total of the highest-revenue consecutive W-day stretch. If several stretches tie, choose the earliest. Avoid recomputing every window from scratch.

Input

First line N W; second line N non-negative integer daily revenues, with 1 <= W <= N <= 1000.

Output

start total for the earliest maximum window.

Example 1

Input

5 2
2 5 1 4 2

Output

0 7

The first two days total seven; later two-day windows total six, five and six, so start zero wins.

Constraints

  • 1 <= W <= N <= 1000.
  • Daily revenues are non-negative integer cents.

Hints

Hint 1 of 2

Update a window by adding the incoming day and subtracting the outgoing day.

Hint 2 of 2

Use a strict greater-than comparison to retain the earliest tie.

Solution

Show a reference solution and explanation
 JavaScript · reference solution
const [n, width] = readline().split(' ').map(Number);
const values = readline().split(' ').map(Number);
let current = values.slice(0, width).reduce((a, b) => a + b, 0);
let best = current, start = 0;
for (let i = width; i < n; i++) {
  current += values[i] - values[i - width];
  if (current > best) { best = current; start = i - width + 1; }
}
console.log(start, best);

Why it works

The first complete window establishes a valid baseline. Each next sum differs by exactly one entering and one leaving day, so the scan is O(N). Updating only for a strictly larger total leaves the earliest tied window selected.

Lesson for this exercise: JavaScript Arrays: Creating, Indexing and Changing Lists

Your program
const [n, width] = readline().split(' ').map(Number);
const values = readline().split(' ').map(Number);
let current = values.slice(0, width).reduce((a, b) => a + b, 0);
let best = current, start = 0;
// Slide the window; preserve the earliest start on a tie.
console.log(start, best);

Tests: 4 cases including the examples. Passing every test marks the exercise solved in this browser.

Ready for a challenge?

How this page was checked. Every program on it was run with Node.js 22 at build time; runs in your browser in an isolated Web Worker by the publishing checks, and the output shown is what it printed. The Run buttons execute the same code on your device; nothing you type is sent anywhere.