E- knapsack 2 from dp contest on atcoder

I am getting WA from 6 test case onwards in the knapsack2 problem on Atcoder. Please help me out with this.
my code: https://ide.codingblocks.com/s/233234

@Yash-Mittal-2335533069896503 just dont break the loop in case dp[n][i] > weight, skip it and keep taking ans = i, if(dp[n][i]<=weight)

@Yash-Mittal-2335533069896503 Also mark the doubt as resolved if your query is resolved.