imashutosh51

Circular tour

Jul 31st, 2022 (edited)
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.92 KB | None | 0 0
  1. '''
  2. * We are given a circular sequence of petrol pumps where each pump provides some petrol and requires some petrol to reach the next pump, and we must find one pump from which the car can start and complete the entire circle
  3.  
  4. * If the car starts from a pump `A` and fails to reach some pump `B`, then none of the pumps between `A` and `B` can be a valid starting point, because starting from any of them would reach pump `B` with even less petrol and again fail
  5.  
  6. * Petrol can only be collected from previous pumps and cannot be borrowed from future pumps, so once a failure occurs all earlier candidates up to that point are permanently discarded
  7.  
  8. * Therefore, whenever a failure happens at some index, all starting points up to that index are eliminated and the next possible candidate must be the following pump
  9.  
  10. * While scanning the pumps from left to right, we keep track of the total surplus petrol obtained from successful segments and the total deficit petrol required at failed points
  11.  
  12. * After completing one full pass, the remaining surplus petrol represents the fuel available to cover all previously encountered deficits
  13.  
  14. * If the remaining surplus petrol is sufficient to compensate for all the deficits, then the chosen starting point can complete the full circle
  15.  
  16. * If the remaining surplus petrol is insufficient, then no starting station exists that can complete the circular tour
  17. '''
  18. class Solution:
  19.     def startStation(self, gas, cost):
  20.         scarsity=0 #here scarsity means,if I start with this much additional petrol at the 0th index,I can reach till the end.
  21.         cur=0
  22.         start=0
  23.         for i in range(len(cost)):
  24.             cur+=gas[i]
  25.             if cur>=cost[i]:
  26.                 cur-=cost[i]
  27.             else:
  28.                 scarsity+=(cost[i]-cur)
  29.                 cur=0
  30.                 start=i+1
  31.         if cur>=scarsity:
  32.             return start
  33.         else:
  34.             return -1
  35.            
Advertisement
Add Comment
Please, Sign In to add comment