fork(1) download
  1. /**
  2.  * Petrol Pump Problem
  3.  * @author Prateek
  4.  */
  5. class PetrolPump {
  6. /**
  7. * Get the Starting Point of the Circular Trip
  8. * @return index of the petrol pump if solution exist ,
  9. * else -1 if solution doesnt exist
  10. */
  11. public static int getStartIndex(int[] dist , int[] petrol){
  12.  
  13. int nPumps= petrol.length;
  14. int start , currentPetrol;
  15. int i=start=0;
  16.  
  17. while(start < nPumps)
  18. {
  19. currentPetrol= petrol[i] - dist[i] ;
  20.  
  21. while(currentPetrol >= 0) {
  22.  
  23. i= (i+1) % nPumps ;
  24.  
  25. currentPetrol += petrol [i] - dist[i] ;
  26.  
  27. if(i==start)
  28. return start;
  29. }
  30.  
  31. start = ++i ;
  32. i= i % nPumps ;
  33. }
  34. return -1;
  35. }
  36.  
  37. public static void main(String[] args) {
  38. int [] dist = {4, 7, 4, 8, 4, 1};
  39. int [] petrol = {3, 5, 3, 8, 3, 6};
  40.  
  41. int index= getStartIndex(dist, petrol);
  42.  
  43. if(index == -1)
  44. System.out.println("Solution Does not exist");
  45. else
  46. System.out.println("Petrol Pump Number : " +(index + 1));
  47. }
  48. }
  49.  
Success #stdin #stdout 0.06s 380160KB
stdin
Standard input is empty
stdout
Petrol Pump Number : 6