์ฝ๋
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int totalGas = 0, totalCost = 0, currentGas = 0;
int start = 0;
for (int i = 0; i < gas.length; i++) {
totalGas += gas[i];
totalCost += cost[i];
currentGas = gas[i] - cost[i];
// ํ์ฌ ์ฐ๋ฃ๊ฐ ์์๊ฐ ๋๋ฉด, ๋ค์ ์ถ๋ฐ์ ์ผ๋ก ๊ฐฑ์
if (currentGas < 0) {
start = i + 1;
currentGas = 0;
}
}
// ์ ์ฒด ๊ฐ์ค๊ฐ ์ ์ฒด ๋น์ฉ๋ณด๋ค ๋ง์ผ๋ฉด ์ํ๊ฐ ๊ฐ๋ฅ
if (totalGas >= totalCost) {
return start;
} else {
return -1;
}
}
}
Java
๋ณต์ฌ
๋ฌธ์ ํด๊ฒฐ ์์ด๋์ด
์ ์ฒด ๊ฐ์ค๊ฐ ์ ์ฒด ๋น์ฉ๋ณด๋ค ๋ง์ผ๋ฉด ๋ฐ๋์ ํ๋์ ์ถ๋ฐ์ ์ด ์กด์ฌํ๊ณ ์ํ๊ฐ ๊ฐ๋ฅํ๋ค.
์ด๋ฅผ ํ์ฉํด์, ํ์ฌ ์ฐ๋ฃ๊ฐ์ ๋ฐ๋ผ ์ถ๋ฐ์ ์ ๊ฐฑ์ ํด๊ฐ๋ฉฐ ๊ทธ๋ฆฌ๋ํ๊ฒ ๋ฌธ์ ํ์ด๊ฐ ๊ฐ๋ฅํ๋ค.