法1:贪心
时间复杂度O(N),N为补给站数量
优化青海湖至景点X的租车路线成本 - MarsCode和这道题一样,只不过每个站点不限量购买,背包容量无限大。加油站题会更难,有最大加油容量限制。
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static int solution(int m, int n, int[][] p) {
// Edit your code here
//最后一天也视为一个不要钱的补给站,方便遍历
int[][] P = new int[n+1][2];
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2; j++) {
P[i][j]=p[i][j];
}
}
P[n][0]=m; P[n][1]=0;
// 按天数排序补给站
Arrays.sort(P, Comparator.comparingInt(a -> a[0]));
int cost = 0;
int curIdx = 0;
int nextIdx = curIdx+1;
while(curIdx!=n) {
if(P[nextIdx][1] < P[curIdx][1]) { //比当前补给站更便宜就到这,最便宜的为终点站
cost += (P[curIdx][1] * (P[nextIdx][0] - P[curIdx][0]));
curIdx = nextIdx;
nextIdx = curIdx+1;
}
else //不更便宜就继续往后看,最多看到终点站,则当前就是就是最便宜的
nextIdx ++;
}
return cost;
}
public static void main(String[] args) {
// Add your test cases here
System.out.println(solution(5, 4, new int[][]{{0, 2}, {1, 3}, {2, 1}, {3, 2}}) == 7);
}
}
法2:动态规划计算每天能购买的最低价格
时间复杂度O(m+n),也可优化为O(n),因为当p遍历完了可以直接计算出后面每天的最便宜价格了
public class Main {
public static int solution(int m, int n, int[][] p) {
// Edit your code here
int minPrice = p[0][1]; //记录每天能吃的最便宜的食物价格
//dp更新minPrice
int idx = 0; //遍历p的下标
int cost = 0;
for (int i = 0; i < m; i++) {
if(idx < n && p[idx][0] == i) {
if(p[idx][1] < minPrice)
minPrice = p[idx][1];
idx++;
}
//计算每天最便宜食物价格
cost += minPrice;
}
return cost;
}
public static void main(String[] args) {
// Add your test cases here
System.out.println(solution(5, 4, new int[][]{{0, 2}, {1, 3}, {2, 1}, {3, 2}}) == 7);
}
}