Trains the technique from
LeetCode 2104Sum of Subarray RangesThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A sailplane carries a barograph that writes down one altitude reading a minute for the whole flight. readings lists them in flight order, each in metres measured against the ridge line the pilot is working, so a reading taken below the ridge is negative.
A stretch is any run of one or more consecutive readings, identified by where it starts and where it ends. The swing of a stretch is its highest reading minus its lowest reading; a stretch holding a single reading therefore swings 0.
Return the sum of the swings of every stretch of readings. A flight of n readings has n * (n + 1) / 2 stretches, and the total can be far larger than a 32-bit integer holds, so it must be returned as a 64-bit value.
Example 1
The five single-minute stretches each swing 0. The four two-minute stretches swing 17, 17, 18 and 35, the three three-minute stretches swing 17, 35 and 35, the two four-minute stretches swing 35 and 35, and the whole flight swings 35, which adds up to the figure returned.
Example 2
Every stretch, however long, has the same highest and lowest reading, so each one swings 0.
Example 3
A single reading forms the only stretch, and its highest and lowest reading are the same.
Example 4
There are three stretches: the two single readings swing 0 each, and the pair swings 2000000000, which is past what a 32-bit integer holds.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def total_swing(readings: list[int]) -> int:public long totalSwing(int[] readings)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.