/**
* Petrol Pump Problem
* @author Prateek
*/
class PetrolPump {
/**
* Get the Starting Point of the Circular Trip
* @return index of the petrol pump if solution exist ,
* else -1 if solution doesnt exist
*/
public static int getStartIndex(int[] dist , int[] petrol){
int nPumps= petrol.length;
int start , currentPetrol;
int i=start=0;
while(start < nPumps)
{
currentPetrol= petrol[i] - dist[i] ;
while(currentPetrol >= 0) {
i= (i+1) % nPumps ;
currentPetrol += petrol [i] - dist[i] ;
if(i==start)
return start;
}
start = ++i ;
i= i % nPumps ;
}
return -1;
}
public static void main
(String[] args
) { int [] dist = {4, 7, 4, 8, 4, 1};
int [] petrol = {3, 5, 3, 8, 3, 6};
int index= getStartIndex(dist, petrol);
if(index == -1)
System.
out.
println("Solution Does not exist"); else
System.
out.
println("Petrol Pump Number : " +(index
+ 1)); }
}
LyoqCiAqIFBldHJvbCBQdW1wIFByb2JsZW0KICogQGF1dGhvciBQcmF0ZWVrCiAqLwogY2xhc3MgUGV0cm9sUHVtcCB7CgkvKioKCSAqIEdldCB0aGUgU3RhcnRpbmcgUG9pbnQgb2YgdGhlIENpcmN1bGFyIFRyaXAKCSAqIEByZXR1cm4gaW5kZXggb2YgdGhlIHBldHJvbCBwdW1wIGlmIHNvbHV0aW9uIGV4aXN0ICwKCSAqICAgICAgICAgICBlbHNlIC0xIGlmIHNvbHV0aW9uIGRvZXNudCBleGlzdAoJICovCglwdWJsaWMgc3RhdGljIGludCBnZXRTdGFydEluZGV4KGludFtdIGRpc3QgLCBpbnRbXSBwZXRyb2wpewoKCQlpbnQgblB1bXBzPSBwZXRyb2wubGVuZ3RoOwoJCWludCBzdGFydCAsIGN1cnJlbnRQZXRyb2w7CgkJaW50IGk9c3RhcnQ9MDsKCgkJd2hpbGUoc3RhcnQgPCBuUHVtcHMpCgkJewoJCQljdXJyZW50UGV0cm9sPSBwZXRyb2xbaV0gLSBkaXN0W2ldIDsKCgkJCXdoaWxlKGN1cnJlbnRQZXRyb2wgPj0gMCkJewoJCQkJCgkJCQlpP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