Suppose there is a circle. You have five points on that circle. Each point corresponds to a petrol pump. You are given two sets of data.
1. The amount of petrol that petrol pump will give.
2. Distance from that petrol pump tp the next petrol pump.
(Assume for 1 lit Petrol the truck will go 1 km)
Now calculate the first point from where a truck will be able to complete the circle.
(The truck will stop at each petrol pump and it has infinite capacity).
Give o(n) solution. You may use o(n) extra space.
Q: (大意)
有一个环型线路,上面有5个加油站。现在你有两组数据
1. 每个加油站储备的油量
2. 当前加油站距离下一加油站的距离
(假设一升油可以跑一公里) 现在请计划,找出第一个加油站,如果汽车从该加油站出发的话,能够跑完整个一圈。
(汽车每跑到一个加油站,可以把所有的油都加上,即假设汽车的油箱足够大)
期望时间复杂度O(n), 可以使用O(n)的空间。
A:
设p[i] 为每个加油站的储油量,d[i]为从加油站p(i)到下一个加油站p(i+1)的距离
创建一个v[i] = p[i] - d[i],表示当前加油站的油,如果用来跑到下一个加油站,还剩下多少(可能为负,表示仅当前加油站的油量,汽车不足以跑到下一个加油站)
所以,实际上是求
1. sum (v[i]) 的和要大于等于零,否则,汽车不可能跑完全程
2. 求v[i]数组中,从某j点出发直至[j-1](即绕一圈回来),sum+=v[j]的值sum始终要大于等于零