豆包补给站最优花费问题——贪心或灵活dp

补给站最优花费问题 - MarsCode

法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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值