Greedy and two pointers
@!multitest, greedy after sorting, two pointers, sliding windows, prefix sums with a Map.
Many Div 2 B problems need one observation and a linear pass. This chapter covers the input shape most of them use (many test cases), then the passes that usually follow a sort: greedy choice, two pointers and a sliding window.
Many test cases
When the input starts with t and then t independent tests, write the
program for one test and put @!multitest on the first line:
Press Run (Ctrl+Enter).
Everything below the line runs once per test, so state can't leak from
one test into the next: each var starts fresh. A return ends only
the current test.
Greedy after sorting
To buy as many items as a budget c allows, buy the cheapest first. Sorting turns the observation into a loop:
Press Run (Ctrl+Enter).
The sort key is often not the obvious one. To keep the most non-overlapping intervals, take them by earliest end:
Press Run (Ctrl+Enter).
When you can't prove a greedy choice, check it: put an exhaustive
@alt(program) in the same file and press Stress (see
Stress testing).
Two pointers
On sorted data, two indices moving towards each other replace a
nested loop. This counts pairs i < j with s[i] + s[j] <= x in
O(n): when the pair at the ends fits, so does every pair between them.
Press Run (Ctrl+Enter).
Sliding windows
Two pointers that move the same way keep a window lo..=hi. With
positive numbers, growing the window only raises its sum, so each end
moves at most n times. The shortest window with sum at least s:
Press Run (Ctrl+Enter).
best starts as None, not a large number, and min= on a ?Int
takes the first value it is given; ?? -1 prints the "no window"
answer.
When numbers can be negative
A window no longer works when a sum can shrink as the window grows.
Count subarrays with sum exactly k with prefix sums and a Map of
how often each prefix sum has appeared:
Press Run (Ctrl+Enter).
Problem: Boat pairs
Each boat holds one or two people with total weight at most x. Print the fewest boats for every test.
Hints
Sort, then pair the lightest person left with the heaviest who fits: the heaviest has to go somewhere, and the lightest is the best partner anyone could give them.
More like this: Budget window. Next: The standard library.
Lints for these patterns
cpl lint, the editor and the playground flag the hand-written versions of what this chapter teaches:
state_above_multitest: State above multitest