From 61b5012d23151a15e59d9a7df24e80a0f7ede11b Mon Sep 17 00:00:00 2001 From: "akash.patil" Date: Tue, 4 Mar 2025 20:07:41 +0530 Subject: [PATCH] Update 1642-furthest-building-you-can-reach.java MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Key Improvements: ✅ Prioritize Bricks First: Instead of assuming ladders are the default, we use bricks first and only replace the smallest brick usage with a ladder when needed. ✅ Avoids Unnecessary Heap Operations: By deferring ladder usage, we reduce heap operations, making it slightly faster. ✅ Better Code Readability: The logic is clearer, and unnecessary checks are avoided. --- .../1642-furthest-building-you-can-reach.java | 32 +++++++++++++------ 1 file changed, 22 insertions(+), 10 deletions(-) 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 によって変換されたページ (->オリジナル) /