Failing two test cases. please help me find where i am doing wrong?
Problem in petrol pumps
I have traversed the array and at every index, i am storing the remaining amount of petrol left or short(have surplus or deficiency) till that point…now at the end …if rem is negative that means we can’t travel since the total petrol required is more…is rem is zero or positive, then
I traverse from the last and find the first occurrence of negative rem(which is stored in gap[i]),
Why have I done this? so that I can store as much of fuel in the start of my journey.
The very next index after the last occurrence of the negative element is my answer.
Please correct me if I am wrong.
Hey @abhir26
Giving u a testcase for which it will fail :
4
8 8 2 10
7 7 5 9
output is 3 urs giving 0(btw u have to return acc to 1-indexed array)
You are picking the one in which u can save maximum petrol but if still total becomes negative later then also its not helpful.
Also the tracks are circular and it was also mentioned that unique answer will be there so do like this
int total = 0 ;
int cur = 0 ;
int s= 0; //S will keep track of starting index
for(int i = 0 ; i < n ; i++){
total += gas[i] - cost[i];
cur += gas[i] - cost[i];
if(curr<0){ //you can't move ith to (i+1)th station,because cost is greater than gas
s=i+1;//update s,can’t possible to move current station i to next station
curr=0//set curr at 0,Whether movement is possible or not for next time
}
}
if(total >= 0 )
return s;
else
return -1;
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.