Q134加油站

思路

在这里插入图片描述
很清晰的可以看到,首先start加油站的left一定要大于0,然后从start开始一直到start-1,currentGas 一定要大于等于0

首先找到合适的start
如果a->b此时currentGas小于0了,则新的start一定从b+1往后找,而不用从a+1往后找。
如果新的start是c,c在a-b之间,首先a-c是大于等于0的,c到b加上a-c的剩余汽油值一定是大于等于c到b的,但是a到b小于0,所以c到b也一定小于0

有点抽象
在这里插入图片描述

代码

public int canCompleteCircuit(int[] gas, int[] cost) {
        int[] left = new int[gas.length];
        int sum = 0;
        for (int i = 0; i < gas.length; i++) {
            left[i] = gas[i] - cost[i];
            sum = sum + left[i];
        }
        if (sum < 0){
            return -1;
        }
        int index = 0;
        int start = 0;
        int currentLeftGas = 0;
        while (index < gas.length){
            if (left[index] >= 0){
                start = index;
                while (index <gas.length){
                    currentLeftGas = currentLeftGas + left[index];
                    if (currentLeftGas < 0){
                        currentLeftGas = 0;
                        start = -1;
                        break;
                    }
                    index++;
                }
            }
            index++;
        }
        if (start == -1){
            return -1;
        }
        for (int i = 0 ;i  < start; i++){
            if(currentLeftGas + left[i] >=0){
                currentLeftGas = currentLeftGas + left[i];
            }
            else {
                return -1;
            }
        }
        return start;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值