diff --git a/1642-furthest-building-you-can-reach/1642-furthest-building-you-can-reach.java b/1642-furthest-building-you-can-reach/1642-furthest-building-you-can-reach.java index 661530e9..e3777e26 100644 --- a/1642-furthest-building-you-can-reach/1642-furthest-building-you-can-reach.java +++ b/1642-furthest-building-you-can-reach/1642-furthest-building-you-can-reach.java @@ -1,16 +1,28 @@ +import java.util.PriorityQueue; + class Solution { public int furthestBuilding(int[] heights, int bricks, int ladders) { - PriorityQueue pq = new PriorityQueue(); - for(int i=0;i0) + PriorityQueue pq = new PriorityQueue(); // Min heap to track used bricks + int i = 0; + + for (; i < heights.length - 1; i++) { + int distance = heights[i + 1] - heights[i]; + + if (distance> 0) { pq.add(distance); - if(pq.size()>ladders) - bricks -= pq.poll(); - if(bricks<0) + } + + // If we have used more ladders than available, replace the smallest ladder use with bricks + if (pq.size()> ladders) { + bricks -= pq.poll(); // Convert the smallest ladder usage into bricks + } + + // If bricks are exhausted, return the last possible building index + if (bricks < 0) { return i; + } } - return heights.length-1; + + return i; // Reached the last building } -} \ No newline at end of file +}

AltStyle によって変換されたページ (->オリジナル) /