Can anyone please take look why this might cause an issue?
The reasoning for the last loop is simply splitting the array into 0…i and i+1…n-1 and checking if this gives minimum cost.
REP(i,n-2) should be there instead of REP(i,n-1).
In your case when i=n-2, 2nd array will contain only one element, the last element. It means the formula of abs(…) will not work.
Thanks for looking into this. The suggestion you made did not help (WA on trying it).
Last line which is causing the issue : REP(i,n-1) ans = min(ans, abs((A[i]-A[0]) - (A[n-1]-A[i+1])));
Here REP is non-inclusive of the limit. So the loop is from 0 to n-2.
I’m simply splitting the array into 0…i and i+1…n-1 (both end-points inclusive). This is achievable by either decreasing A[0] or increasing A[n-1] as necessary by the value computed in the abs() part.
So if this is affecting the answer, then this should be the minimum since it is achievable. If not the solution has to pass like the AC solution mentioned in the post.
Thanks for the insight. I didn’t think it through when I read your response. Yes, the abs() part breaks down at end points, i.e. both at i=0 and i=n-2. Since at these points, we won’t be able to reach that minimum.
I changed the loop to 1 to n-3 and got AC (submission).
and say what I did wrong , I found my own logic which seems to be right for many test cases I tried , can anyone also suggest some testcases in which my code fails to produce correct answer .