import java.util.PriorityQueue;
/**
* @author xnl
* @Description:
* @date: 2022/7/2 22:57
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
// int[][] stations = {{10,60},{20,30},{30,30},{60,40}};
int[][] stations = {{60, 50}};
// int[][] stations = {{14,123},{145,203},{344,26},{357,68},{390,35},{478,135},
// {685,108},{823,186},{934,217},{959,80}};
System.out.println(solution.minRefuelStops2(100, 50, stations));
}
/**
* 动态规划,统计加油次数最多可以到达的最远距离
* 我们使用一个stations的长度来计算最大的可以加油的距离
* @param target
* @param startFuel
* @param stations
* @return
*/
public int minRefuelStops(int target, int startFuel, int[][] stations) {
int n = stations.length;
// 存储每一个的最大距离
long[] dp = new long[n + 1];
dp[0] = startFuel;
for (int i = 0; i < n; i++){
for (int j = i; j >= 0; j--){
// 如果最大距离是可以到达的距离
if (dp[j] >= stations[i][0]){
// 更新每一次加油可以到达的最远距离
dp[j + 1] = Math.max(dp[j + 1], dp[j] + stations[i][1]);
}
}
}
for (int i = 0; i <= n; i++) {
if (dp[i] >= target ){
return i;
}
}
return - 1;
}
public int minRefuelStops2(int target, int startFuel, int[][] stations) {
int n = stations.length;
PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> b - a);
// prev 上一个位置, fuel 当前位置燃料
int ans = 0, prev = 0, fuel = startFuel;
for (int i = 0; i <= n; i++){
int curr = i < n ? stations[i][0] : target;
// 减去当前位置的值,计算可以走多远
fuel -= curr - prev;
while (fuel < 0 && !queue.isEmpty()){
fuel += queue.poll();
ans++;
}
if (fuel < 0){
return -1;
}
if (i < n){
queue.offer(stations[i][1]);
prev = curr;
}
}
return ans;
}
}
07-03
234
12-11