intermediate · greedy · circular array · running sum

Where to start a round trip on a fuel budget

Problem

A delivery drone flies a fixed loop of charging pads 0, 1, …, n − 1 and back to 0. At pad i it picks up fuel[i] units of charge; flying from pad i to the next pad uses cost[i] units. The battery starts empty and has no upper limit.

Return the smallest pad index from which the drone can complete the whole loop without the battery ever going below zero, or −1 if no pad works.

Constraints

  • 1 ≤ n ≤ 20
  • fuel[i] and cost[i] from 0 to 99

Examples

fuel = [1, 2, 3, 4, 5], cost = [3, 4, 5, 1, 2] → 3

fuel = [2, 3, 4], cost = [3, 4, 3] → -1 — Total fuel 9 < total cost 10.

Show the solution

One pass with restarts

Arriving at a pad with a non-negative battery never hurts. So if starting at s fails at pad i, starting anywhere between s and i arrives at i with even less, and fails too.

Why it is correct

Let gain[i] = fuel[i] − cost[i] and T the total gain. Ruling out: if the battery from s first goes negative at pad i, every running sum from s to j − 1 (j ≤ i) is ≥ 0, so the sum from j to i is negative and no start in s…i works; hence every index before the final start fails. Sufficiency when T ≥ 0: from the final start to n − 1 the running sum S never drops below 0. Pads 0…start − 1 split into failed segments, each with a negative total but non-negative proper prefixes, so every prefix sum over 0…j is at least the total over 0…start − 1, which is T − S. The battery at pad j is therefore at least S + (T − S) = T ≥ 0. If T < 0, a full loop loses charge, so no start works.

Complexity

Time O(n), extra space O(1). Each pad is visited once; a restart only moves the candidate forward.

For contrast: Simulate the full loop from every pad in order and return the first that never goes negative. That costs O(n²) time and O(1) space.

Edge cases

  • One pad: works if fuel ≥ cost.
  • Total gain exactly 0: some start works.
  • Several valid starts: the smallest one is returned.

Common mistakes

  • Restarting at s + 1 instead of i + 1, which is correct but O(n²).
  • Returning the start without checking the total gain.

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class FuelLoopStart
{
    /// <summary>Smallest start pad that completes the loop with a never-negative battery, or -1. O(n) time, O(1) space.</summary>
    public static int Find(int[] fuel, int[] cost)
    {
        int total = 0, tank = 0, start = 0;
        for (int i = 0; i < fuel.Length; i++)
        {
            int gain = fuel[i] - cost[i];
            total += gain;
            tank += gain;
            if (tank < 0)
            {
                start = i + 1; // no pad in start..i can work
                tank = 0;
            }
        }
        return total >= 0 ? start : -1;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/FuelLoopStart.cs

from collections.abc import Sequence
 
 
def find(fuel: Sequence[int], cost: Sequence[int]) -> int:
    """Smallest start pad that completes the loop with a never-negative battery, or -1. O(n) time, O(1) space."""
    total = tank = start = 0
    for i in range(len(fuel)):
        gain = fuel[i] - cost[i]
        total += gain
        tank += gain
        if tank < 0:
            start = i + 1  # no pad in start..i can work
            tank = 0
    return start if total >= 0 else -1

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/fuel_loop_start.py

package dev.bekadan.dsa.problems;
 
public final class FuelLoopStart {
    private FuelLoopStart() {
    }
 
    /** Smallest start pad that completes the loop with a never-negative battery, or -1. O(n) time, O(1) space. */
    public static int find(int[] fuel, int[] cost) {
        int total = 0;
        int tank = 0;
        int start = 0;
        for (int i = 0; i < fuel.length; i++) {
            int gain = fuel[i] - cost[i];
            total += gain;
            tank += gain;
            if (tank < 0) {
                start = i + 1; // no pad in start..i can work
                tank = 0;
            }
        }
        return total >= 0 ? start : -1;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/FuelLoopStart.java

#pragma once
 
#include <cstddef>
#include <span>
 
namespace bekadan::dsa::problems {
 
// Smallest start pad that completes the loop with a never-negative battery, or -1. O(n) time, O(1) space.
inline int fuel_loop_start(std::span<const int> fuel, std::span<const int> cost) {
    int total = 0, tank = 0;
    std::size_t start = 0;
    for (std::size_t i = 0; i < fuel.size(); ++i) {
        const int gain = fuel[i] - cost[i];
        total += gain;
        tank += gain;
        if (tank < 0) {
            start = i + 1;  // no pad in start..i can work
            tank = 0;
        }
    }
    return total >= 0 ? static_cast<int>(start) : -1;
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/fuel_loop_start.hpp