Skip to content
BytePatterns

How Far Bricks and Ladders Go

MediumHeaps#min-heap#greedy~30m

Problem

A climber walks along a row of rooftops, heights[0] first. Stepping down or to an equal height is free. Stepping up by d needs either one ladder, whatever the height, or d bricks. Given a number of bricks and a number of ladders, return the index of the furthest rooftop the climber can reach when the resources are used as well as possible.

Examples

Input:  heights = [4, 2, 7, 6, 9, 14, 12], bricks = 5, ladders = 1
Output: 4
Why:    bricks for the rise of 5 onto index 2, the ladder for the rise of 3 onto index 4; the rise of 5 after that is too much
Input:  heights = [4, 12, 2, 7, 3, 18, 20, 3, 19], bricks = 10, ladders = 2
Output: 7
Input:  heights = [1, 5], bricks = 0, ladders = 0
Output: 0
Why:    edge case, the very first climb cannot be paid for

Hints

0 / 3

Stuck on the idea rather than the code? Priority Queue covers it.