‹ back to the board

Wednesday, September 16

Adeptalgorithms & data structures

The Cooper's Even Stack

The cooper of bitwick rolls her barrels down the cellar ramp in a fixed order, and she will not reorder them. A run of barrels standing next to each other in that ramp order can be bound into a single banded stack only if the heaviest barrel in the run and the lightest barrel in the run differ by at most limit pounds.

You are given weights, a list of positive integers giving the barrel weights in ramp order, and limit, a non-negative integer.

Write longestBandedRun(weights, limit), which returns an integer: the number of barrels in the longest contiguous run of weights whose largest and smallest values differ by at most limit. If weights is empty, return 0.

  • two pointers and sliding windows
  • Adept

examples

  1. case 1weights of [8, 2, 4, 7], limit of 42 — the run [2, 4] spans 2 pounds; adding 7 to it would span 5, and 8 stands alone
  2. case 2weights of [4, 2, 2, 2, 4, 4, 2, 2], limit of 03 — with no slack at all, only equal neighbours band together, and the longest such run is the three 2s
  3. case 3weights of [], limit of 30 — nothing on the ramp, nothing to band
reward
300 XP
signature
longestBandedRun
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…
  • the eight-pound oak stands alone
  • the long middle run
  • banded only by exact weight
  • an empty cellar
  • a single barrel with no slack
  • the whole ramp bands at once
  • the cooper's full ramp
The Cooper's Even Stack · bitwick