Well there's one test case in the comments below which i used to solve this issue.

Consider (3 1 1 2 5 1 3 4) in an intuitive way i will swap 4 with 1 which results 5 + 3, but if i swap 5 with 1 the outcome will become 5 + 2 due to line 30 condition where 5 + max(2, 1) < 5 + max(3, 1).

This approach was my first shot and it passed both tasks where i fail now.

My current approach assumes that this method selects the best possible swap, but i couldn't actually prove or disprove it.

Thank you for your help.