I was able to solve the problem. The problem has a condition that no element can be bigger than 7. I am trying to figure out if there is a solution for the problem when we don't have this condition. if we take the testcase :-
1 1 2 4 5 25
It's not possible to solve the problem by my method now.