What is mistake in my code

@spagire4
The issue is with line 66
You are multiplying entire component of value with all other component sizes
That is not correct
You need to do
res=(res+(n-size[ans]));
Remove line 63 since that is also a component of size 1