Gas Station - C Solution

1. Introduction

This blog post delves into a practical problem often encountered in route optimization and algorithmic challenges - the "Gas Station" problem. The problem involves finding a starting point in a circular route from which a car can complete the circuit given specific constraints on fuel consumption and availability.

Problem

Given two integer arrays gas and cost, representing the amount of gas available at each gas station and the cost in gas to travel to the next station respectively, the task is to find the starting gas station's index from which you can travel around the circuit once in a clockwise direction. If it's not possible, return -1. The solution must be unique if it exists.

2. Solution Steps

1. Check if the total amount of gas is less than the total cost. If yes, return -1.

2. Initialize variables for the starting index (start) and remaining gas (tank).

3. Iterate through each gas station.

4. Update tank by adding gas available and subtracting the cost.

5. If tank becomes negative at any point, reset it to zero and update the starting index to the next station.

6. The first index where you can complete the circuit is the solution.

3. Code Program

#include <stdio.h>

// Function to find the starting gas station's index
int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize) {
    int total = 0, tank = 0, start = 0;

    for (int i = 0; i < gasSize; i++) {
        total += gas[i] - cost[i];
        tank += gas[i] - cost[i];

        // If tank is negative, you can't start from this or any previous station
        if (tank < 0) {
            start = i + 1; // Set start to the next station
            tank = 0;      // Reset tank
        }
    }

    return total >= 0 ? start : -1; // Check if the circuit can be completed
}

// Main function to test the canCompleteCircuit function
int main() {
    int gas1[] = {1, 2, 3, 4, 5};
    int cost1[] = {3, 4, 5, 1, 2};
    printf("Starting index (Example 1): %d\n", canCompleteCircuit(gas1, 5, cost1, 5));

    int gas2[] = {2, 3, 4};
    int cost2[] = {3, 4, 3};
    printf("Starting index (Example 2): %d\n", canCompleteCircuit(gas2, 3, cost2, 3));

    return 0;
}

Output:

Starting index (Example 1): 3
Starting index (Example 2): -1

Explanation:

1. int total = 0, tank = 0, start = 0; - Initialize total gas, tank, and starting index.

2. for (int i = 0; i < gasSize; i++) - Iterate through each gas station.

3. total += gas[i] - cost[i]; - Update total gas.

4. tank += gas[i] - cost[i]; - Update tank gas after each station.

5. if (tank < 0) - Check if the tank is negative, indicating you can't start from the current or any previous station.

6. start = i + 1; and tank = 0; - Reset starting index and tank.

7. return total >= 0 ? start : -1; - Return the starting index if possible, otherwise -1.

8. The main function tests the canCompleteCircuit function with two examples and prints the starting index.


Comments