Why is my code for the Knapsack problem on CodeChef not working?

Here’s my code: https://ideone.com/TlAzrj
Here’s the problem statement: https://www.codechef.com/problems/KNAPSACK

This passes the example test case. However I get a Wrong Answer (WA) while submitting.

The code works on the SPOJ version of the problem as well, when modified to suit the input format of the SPOJ version.

Here’s my code for the SPOJ version: https://ideone.com/z8SuKK
Here’s the SPOJ problem statement: https://www.spoj.com/problems/KNAPSACK/

Please help.