LeetCode 풀기 - 134. Gas Station

백지우·2026년 9월 15일

LeetCode

목록 보기
51/76
  • LeetCode 최소 하루에 하나는 풀자는 마인드
  • 사용언어: JAVA

134. Gas Station

풀이

  • 방법: 진행하다가 현재 cost가 0이하로 떨어지면 시작 위치가 될 수 없음.
class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int res = 0;
        int curCost = 0;
        int total = 0;

        for(int i = 0; i < gas.length; i++){
            curCost += gas[i] - cost[i];
            total += gas[i] - cost[i];
            if(curCost < 0){
                res = i+1;
                curCost = 0;
            }
        }

        if(total >= 0 && res != cost.length) return res;
        else return -1;
    }
}

0개의 댓글