25.3: 加油站良好出发点问题

package algorithmbasic.basicsets.class25;

import java.util.LinkedList;

/**
 * 加油站良好出发点问题
 */
public class GasStation {
    public static int canCompleteCircuit(int[] gas, int[] cost) {
        /*1:进行简化,简化的方法:gas - cost*/
        int[] arr = new int[gas.length];
        for (int i = 0; i < gas.length; i++) {
            arr[i] = gas[i] - cost[i];
        }
        /*2:构造累加和数组并进行扩充*/
        int[] res = new int[arr.length * 2 - 1];
        res[0] = arr[0];
        for (int i = 1; i < res.length; i++) {
            res[i] = res[i - 1] + arr[i % arr.length];
        }
        /*3:使用滑动窗口,检索窗口内最小值是否小于0*/
        return slidingWindowMinArray(res, arr.length);
    }

    public static int slidingWindowMinArray(int[] res, int Lend) {
        LinkedList<Integer> minWindow = new LinkedList<>();
        int R = 0;
        for (int L = 0; L < Lend; L++) {
            while (R < Lend + L) {
                while(!minWindow.isEmpty() && res[minWindow.peekLast()] >= res[R] ) {
                    minWindow.pollLast();
                }
                minWindow.addLast(R);
                R++;
            }
            if((L != 0 && res[minWindow.peekFirst()] - res[L - 1] >= 0) || (L == 0 && res[minWindow.peekFirst()] >= 0)) {
                return L;
            }
            while(!minWindow.isEmpty() && minWindow.peekFirst() <= L) {
                minWindow.pollFirst();
            }
        }
        return -1;
    }


    public static void main(String[] args) {
        int[] gas = {3,1,1};
        int[] cost = {1,2,2};
        int ans = canCompleteCircuit(gas, cost);
        System.out.println(ans); //0
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HackerTerry

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值