Data Structures & AlgorithmsVery hardCodeforces Div2 C · GATE CS

A circular route has gas stations with gas = [1, 2, 3, 4, 5, 2] and travel cost to the next station = [3, 4, 5, 1, 2, 3]. You start with an empty tank at one station and must complete the full circle. Which starting station index (0-based) is valid? If several valid stations exist, choose the smallest index; report −1 if none exists.

  1. A. -1
  2. B. 3
  3. C. 5
  4. D. 0

Correct answer: A. -1

Compute the total surplus: if it is negative, no start works. Otherwise, the start is just after the point where the running surplus is lowest, because any prefix before that point cannot be left with a deficit. Starting at the station with most gas is a wrong heuristic.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic