Problem — link My solution — link
I genuinely feel there is a minor mistake in the code so, I would like to receive some help in spotting that instead of being introduced to some new approach. I love different approaches for one problem but this is different, I want to know why this one does not work. Have a look please.
UPD: A/C Solution: link
2 mistakes
1. check if the
a[0] - 1 > x
. if true output x.2.
if (a[i] - a[i - 1] > 1 && x > 0)
change it toif (a[i] - a[i - 1] > 1 && x >= 0)
Thanks for pointing out. It helped.
The mistake is you allow gaps to exist in the input. For example:
Your code outputs 10 even tho the answer is 6. To solve this you can stop the for loop when x==0 i. e.
for(i=1;i<n && x;++i)
. However, if you'd run the new code you'd get the answer 4 because we aren't taking into consideration the following 5 and 6. To solve this you can add a while loop likewhile(a[i]-a[i-1]==1 && i<n) {ans++; i++;}
which increases ans but only if there are no gaps(it stops at the first gap).If u observe numbers in the array are in [1,100] and n also in [1,100] . So u can try it in this way too : 124977131