Maximize the feasible answer
Updated
Maximum feasible speed here is the largest speed that still needs at least H hours: hours(speed) >= H. That predicate is true on a prefix of speeds. Use a bias-up mid, or take the first infeasible speed and subtract 1.
What to focus on
If you set L = mid with mid = Math.floor((L+R)/2) you stick (L=0 R=1 style, now on speeds). For a = [4, 1, 9] and H = 4 the max speed with hours >= 4 is 8.
Worked examples
H=4 → speed 8
a = [4, 1, 9], H = 4- feasible = hours>=4; mid = Math.floor((L+R+1)/2)
- L=1 R=9 mid=5 hours=4 >=4 so L=5
- L=5 R=9 mid=7 hours=4 >=4 so L=7
- L=7 R=9 mid=8 hours=4 >=4 so L=8
- L=8 R=9 mid=9 hours=3 <4 so R=8
- L=8 R=8
Result: max speed 8
H=5 → speed 4
a = [4, 1, 9], H = 5- L=1 R=9 mid=5 hours=4 <5 so R=4
- L=1 R=4 mid=3 hours=6 >=5 so L=3
- L=3 R=4 mid=4 hours=5 >=5 so L=4
- L=4 R=4
Result: max speed 4
stuck if L=mid and floor mid
a = [4, 1, 9], H = 4, wrong L=mid with mid=Math.floor((L+R)/2)- reach L=8 R=9 mid=8 hours=4 >=4
- L=mid=8, still L=8 R=9 mid=8
Result: infinite loop at mid=8
Try it
Write maxSpeedAtLeastH(a, H). a is the pile array. H is the hour floor. L, mid, and R are speeds. Use bias-up mid = Math.floor((L+R+1)/2) so L = mid does not stick. Return the maximum speed with hours >= H. [4, 1, 9] H=4 → 8 H=5 → 4 Wrong L=mid with floor mid → infinite loop at mid=8
Piles a are positive integers, non-empty. Speeds are integers in 1..max(a). H is a positive integer. L, mid, and R are speeds.