Skip to the code
+25 XP

#595 Loop Route Starting Station

medium

A delivery drone flies a loop through n charging pads, numbered 0 to n - 1, and back to pad 0. At pad i it picks up gain[i] units of charge, and flying from pad i to the next pad uses cost[i] units. Its battery starts empty and has no limit, and the charge must never go below zero during the trip.

Write startingPad(gain, cost) that returns the smallest index of a pad where the drone can start and fly the whole loop back to that pad, or -1 if no pad works.

Example 1

Input: gain = [3,1,2,5,4], cost = [4,3,1,2,5]
Output: 2

Starting at pad 2: charge goes 2 - 1 = 1, then 1 + 5 - 2 = 4, then 4 + 4 - 5 = 3, then 3 + 3 - 4 = 2, then 2 + 1 - 3 = 0.

Example 2

Input: gain = [2,3,4], cost = [3,4,3]
Output: -1

The pads give 9 units in total, but the loop costs 10.

Constraints

  • 1 <= gain.length === cost.length <= 100000
  • 0 <= gain[i], cost[i] <= 10^4
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).