Getting incorrect testcases

i have solved the problem but it is not working for some of the test cases and I also wanted to know whether there is an easier way to solve the problem