solution link:- https://www.codechef.com/viewsolution/27971831
Consider the testcase:
1 12 4 6 29 24 29