Embercode
✕
Greedy AlgorithmsQuick quiz

Gas station

6 questions. Covers Gas station: circular greedy.

Questions 1 to 5 of 6

  1. 1. For gas = {1, 2, 3, 4, 5} and cost = {3, 4, 5, 1, 2}, what is the total of gas[i] - cost[i] over all five stations?
  2. 2. Why does the greedy restart at station i + 1 when the tank goes below zero at station i, instead of restarting at station i?
  3. 3. True or false, with the reason: the total check is needed, because for gas = {2, 3, 4} and cost = {3, 4, 3} the reset walk alone returns a station, even though no start can finish the lap.
  4. 4. True or false, with the reason: if the code moves the start on a failure but never resets tank, it returns the wrong station for gas = {1, 2, 3, 4, 5} and cost = {3, 4, 5, 1, 2}.
  5. 5. What does this program print? ``cpp #include <iostream> #include <vector> int canCompleteCircuit(const std::vector<int>& gas, const std::vector<int>& cost) { long long total = 0; long long tank = 0; std::size_t start = 0; for (std::size_t i = 0; i < gas.size(); ++i) { const long long change = static_cast<long long>(gas[i]) - cost[i]; total += change; tank += change; if (tank < 0) { start = i + 1; tank = 0; } } return total < 0 ? -1 : static_cast<int>(start); } int main() { std::cout << canCompleteCircuit({5, 1, 2, 3, 4}, {4, 4, 1, 5, 1}) << '\n'; } ``

5 question(s) left on this page.