rocksc30 / LeetCode

用于力扣刷题打卡
2 stars 0 forks source link

134. 加油站 #106

Open rocksc30 opened 1 year ago

rocksc30 commented 1 year ago
class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int n = gas.length;
        if(n == 1 && gas[0] >= cost[0]) return 0;
        int ans = -1;
        for (int i = 0; i < n; i++){
            if (gas[i] <= cost[i]){
                continue;
            }
            if (helper(gas, cost, i)){
                ans = i;
                break;
            }
        }
        return ans;
    }

    private boolean helper(int[] gas, int[] cost, int i) {
        int n = gas.length;
        int count = 0;
        int sum = 0;
        while (count++ < n){
            if (i == n){
                i = 0;
            }
            sum += gas[i];
            sum -= cost[i];
            if (sum < 0)
                return false;
            i++;
        }
        return true;
    }
}