Explain how you would implement a custom waterfall layout algorithm for a dynamic grid of items with varying heights.