Can this be solved without recussion

in this code i tried to solve without recurrsion but half the test cases gives wrong ans