Boss lesson · Unit 01
The biggest tank
Container with most water: move the shorter wall
What you practise
- Move the shorter wall
- The greedy argument
Try a question from this lesson
Pick one
Water between two walls = distance × shorter wall. You start with the two outermost walls, the widest pair. To have any chance of holding more, which wall must go?
Correct answer
The shorter one
Why
Any other pair is narrower. Keep the shorter wall and the water level is still capped by it, so every such pair holds less. Only giving up the shorter wall can pay for the lost width.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Boss: container with most water
Each number is the height of a wall, one unit apart. Pick two walls. The water they hold is the distance between them times the shorter wall.
Find the pair that holds the most. Trying every pair works, in O(n²). You can do it in one pass.
def area(h, i, j):
return (j - i) * min(h[i], h[j])
walls = [1, 8, 6, 2, 5, 4, 8, 3, 7]
print(area(walls, 1, 8)) # 49function area(h, i, j) {
return (j - i) * Math.min(h[i], h[j]);
}
const walls = [1, 8, 6, 2, 5, 4, 8, 3, 7];
console.log(area(walls, 1, 8)); // 49function area(
h: number[], i: number, j: number,
): number {
return (j - i) * Math.min(h[i], h[j]);
}
const walls = [1, 8, 6, 2, 5, 4, 8, 3, 7];
console.log(area(walls, 1, 8)); // 49TypeScript noteEvery parameter needs its own annotation: h: number[], i: number, j: number. There is no shorthand for "the same type again".
10 more exercises in the app
- 4× type the answer
- 1× fill the blanks
- 3× multiple choice
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.