在一條環路上有 N 個加油站,其中第 i 個加油站有汽油 gas[i] 升。 你有一輛油箱容量無限的的汽車,從第 i 個加油站開往第 i+1 個加油站須要消耗汽油 cost[i] 升。你從其中的一個加

List<Integer> list = new ArrayList<>();
        
        for(int i= 0; i < gas.length; i++){
            if(gas[i]>=cost[i]){ 
                 list.add(i);
            }
        }
     
        for(int n = 0; n<list.size(); n++ ){
             
             int j = list.get(n);
             int sum = gas[j];
             //System.out.println(list.get(n));
             while( j < gas.length-1 ){
                sum = sum-cost[j];
                if(sum < 0){
                    break;
                }
                j++;
                sum+=gas[j];
             }
            sum-=cost[j];
            
            if(sum<0){
                continue;
            }
            j=0;
            sum=sum+gas[j];
            while( j != list.get(n)){
                //System.out.println(",,,,,,,");
                sum=sum-cost[j];
                if(sum < 0){
                   break;
                }
                j++;
                sum+=gas[j];
            }
            sum -= cost[list.get(n)];
            if(sum>=0){
                //System.out.println(list.get(n));
                return list.get(n);
            }
           
        }  
        return -1;
相關文章
相關標籤/搜索