Find the max water area between two unsorted fence posts
A farm builds temporary water reservoirs along a straight fence line. Workers pick two fence posts, stretch a waterproof sheet between them, and fill it up. The water can only rise as high as the shorter of the two posts before it spills over, and the posts between them are thin and do not matter. Help the planner find the largest reservoir.
Implement maxReservoir(posts). It returns the largest cross-section area of water that two posts can hold.
maxReservoir(posts) // => number
posts is an array of { x, height } objects. x is the post’s position along the fence (an integer, possibly negative) and height is a non-negative integer.x.a and b hold min(a.height, b.height) * |a.x - b.x| units of water.0 when there are fewer than two posts.posts or the post objects.// Evenly spaced: heights 3, 9, 4, 7, 2, 8 at x = 0..5
maxReservoir([
{ x: 0, height: 3 }, { x: 1, height: 9 }, { x: 2, height: 4 },
{ x: 3, height: 7 }, { x: 4, height: 2 }, { x: 5, height: 8 },
]);
// => 32 (posts at x = 1 and x = 5: min(9, 8) * 4)
// Uneven spacing: the far-apart short pair wins
maxReservoir([
{ x: 11, height: 6 }, { x: 0, height: 5 }, { x: 10, height: 3 }, { x: 2, height: 1 },
]);
// => 55 (x = 0 and x = 11: min(5, 6) * 11)
// Tall posts in the middle do not matter
maxReservoir([{ x: 0, height: 2 }, { x: 5, height: 100 }, { x: 10, height: 2 }]);
// => 20
maxReservoir([{ x: 4, height: 10 }]); // => 0
maxReservoir([]); // => 0