Instagram
youtube
Facebook
Twitter

Truck Tour| Queue

TASK(hard)

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump.

Initially, you have a tank of infinite capacity carrying no petrol. You can start the tour at any of the petrol pumps. Calculate the first point from where the truck will be able to complete the circle. Consider that the truck will stop at each of the petrol pumps. The truck will move one kilometer for each litre of the petrol.

Input Format

The first line will contain the value of N.
The next N lines will contain a pair of integers each, i.e. the amount of petrol that petrol pump will give and the distance between that petrol pump and the next petrol pump.

Constraints:

1<=N<=105

1<=amount of petrol, distance <=109

Output Format

An integer which will be the smallest index of the petrol pump from which we can start the tour.

Sample Input

3

1 5

10 3

3 4

Sample Output

1

SOLUTION 1

def truckTour(petrolpumps):

    petrolRest = [pump[0]-pump[1] for pump in petrolpumps] * 2

    for i in range(len(petrolpumps)):

        tank = 0

        for j in range(i, i + len(petrolpumps)):

            tank += petrolRest[j]

            if tank < 0: break     

        if tank < 0: continue

        else: return i

    return -1

SOLUTION 2

def truckTour(petrolpumps):

    # Write your code here

    nums, total_num = petrolpumps, len(petrolpumps)

    p1, p2 = 0, 0

    oil, dist = nums[p1][0], nums[p1][1]

    while p2 - p1 < total_num:

        if oil < dist:

            i = p1 % total_num

            oil -= nums[i][0]

            dist -= nums[i][1]

            p1 += 1

        else:

            p2 += 1

            i = p2 % total_num

            oil += nums[i][0]

            dist += nums[i][1]

    return p1

EXPLANATION STEPS

1. Initialization:

  • start_index is initialized to 0 as the starting index of the circular route. current_petrol starts at 0 to keep track of the petrol available as we progress.
  • total_petrol accumulates the overall petrol surplus to check if a valid starting index exists.

2. Traversal:

  • Iterate through each petrol pump (petrol, distance) in the petrolpumps list. Update total_petrol similarly to keep track of the surplus petrol.
  • If current_petrol becomes negative, reset start_index to the next pump (i + 1) and reset current_petrol to 0.