Issue with solution for EQBEAUTY problem in SnackDown

This is an accepted submission - https://www.codechef.com/viewsolution/53011854
This one has failed even though there is no reason why the last loop is causing in issue - https://www.codechef.com/viewsolution/53011870

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.

This is what I’m not able to understand.

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).

Can anyone check my code

https://www.codechef.com/viewsolution/52960001

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 .

Try this testcase:

1
5
1 8 8 9 9

The correct answer is 2