[Geeks for Geeks] Circular tour

Circular tour

Suppose there is a circle. There are N petrol pumps on that circle. You will be given two sets of data.

  1. The amount of petrol that every petrol pump has.
  2. Distance from that petrol pump to the next petrol pump.

Find a starting point where the truck can start to get through the complete circle without exhausting its petrol in between.

Note : Assume for 1 litre petrol, the truck can go 1 unit of distance.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:

//Function to find starting point where the truck can start to get through
//the complete circle without exhausting its petrol in between.
int tour(petrolPump p[], int n) {
int res = 0, mi = 0, cur = 0;
for(int i = 0; i < n; i++) {
if(mi > cur) {
mi = cur;
res = i;
}
cur += p[i].petrol - p[i].distance;
}

cur = 0;
for(int i = 0; i <= n; i++) {
if(cur < 0) return -1;
cur += p[(i + res) % n].petrol - p[(i + res) % n].distance;
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/22/PS/GeeksforGeeks/circular-tour/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.