‹ back to the board

Sunday, September 6

Adeptalgorithms & data structures

The Barge of Even Keel

## The Barge of Even Keel

The wharf at bitwick loads its flat-bottomed barge straight off the quay. The crates sit in a fixed line along the stones, and the dockhands lift them in order: they pick a starting crate and an ending crate and take every crate between the two. Nothing is skipped and nothing is reordered. The barge floats level only if the heaviest crate aboard and the lightest crate aboard are close enough in weight.

You are given weights, a list of integers giving the crate weights in quay order (values may be negative, and the list may be empty), and limit, a non-negative integer.

Write evenKeel(weights, limit), which returns an integer: the length of the longest contiguous run of weights in which the largest value minus the smallest value is at most limit. A run of one crate always qualifies. If weights is empty, return 0.

  • two pointers and sliding windows
  • Adept

examples

  1. case 1weights of 1, 5, 3, 4, 2 and limit of 23 — the run 5, 3, 4 spans a difference of exactly 2 (the run 3, 4, 2 is equally long)
  2. case 2weights of 4, 2, 2, 2, 4, 4, 2, 2 and limit of 13 — a 4 and a 2 differ by 2, so only equal weights may share the barge, and the longest equal run is 2, 2, 2
  3. case 3an empty list of weights and limit of 50
reward
320 XP
signature
evenKeel
not yet run

TypeScript, run as ES2022 — types are stripped, not checked. If a JS engine would run it, so will we.

loading the editor…
  • mixed weights, limit 2
  • limit of zero needs equal weights
  • empty quay
  • single crate, zero limit
  • all crates identical
  • steadily rising weights
  • negative weights
  • whole quay fits
  • spike splits the line
The Barge of Even Keel · bitwick