Gas Station (Java)

本文介绍了一种算法,用于确定是否可以在环形路线上找到一个起点,使得一辆油箱无限大的汽车能够通过适当的加油策略完成一次完整的环路旅行。算法考虑了每个加油站提供的汽油量与从该站行驶到下一站所需的汽油成本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

There are N gas stations along a circular route, where the amount of gas at station i is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.

Note:
The solution is guaranteed to be unique.

维护sum代表途径的station的gas[i] - cost[i]的和,total代表所有station的gas[i] - cost[i]的和,如果total < 0,是不可能存在解的,因为总收入小于总支出任何一条路径都无法回到原点。当sum<0的时候,就将loc指向下一个station,因为之前的station所走的路一定无法到达。

Source

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        if(gas.length == 0 || cost.length == 0 || cost.length != gas.length)
        	return -1;
        int loc = 0, sum = 0, total = 0;
        for(int i = 0; i < gas.length; i++){
        	sum += gas[i] - cost[i];
        	total += gas[i] - cost[i];
        	if(sum < 0){
        		loc = i + 1;
        		sum = 0;
        	}
        }
        if(total < 0) return -1;
        else return loc;
    }
}


Test

    public static void main(String[] args){
    	
    	int[] gas = {5};
    	int[] cost = {4};

    	int a = new Solution().canCompleteCircuit(gas, cost);

    	System.out.println(a);
  
    
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值