Untitled

 avatar
unknown
plain_text
15 days ago
1.0 kB
3
Indexable
public class MinRefuelingStops {
    public static int minRefuelStops(int target, int startFuel, int[][] stations) {
        PriorityQueue<Integer> pq_maxheap = new PriorityQueue<>((a, b) -> b - a); // Max heap for fuel
        int maxPoint = startFuel, count = 0, i = 0;
	while(stations[i][0]<=maxPoint)
	{
	    pq_maxheap.add(stations[i][1]);
	    i++;
	}

        while (maxPoint < target && !pq_maxheap.isEmpty()) {
            
            int largestFuel = pq_maxheap.poll();
	    count++;
            maxPoint += largestFuel;

            while (i < stations.length && stations[i][0] <= maxPoint) {
                pq_maxheap.add(stations[i][1]);
                i++;
            }
        }

        return maxPoint < target ? -1 : count;
    }

    public static void main(String[] args) {
        int target = 100;
        int startFuel = 10;
        int[][] stations = {{10, 60}, {20, 30}, {30, 30}, {60, 40}};

        System.out.println(minRefuelStops(target, startFuel, stations)); // Output: 2
    }
}
Leave a Comment