Fill the bags

Please tell me the exact logic to solve this question. I’ve tried a lot but always end up with WA. Here is the link of the question -

It w1 is odd, the we need one n1 object to fill the last one space. If n1==0, then the point is wasted.
so, if w1 is odd, then subtract 1 from it (the last space), if n1>0, add 1 to answer and reduce one from n1. Do the same for w2.

Now you have two bags each with even number weight capacity. Now, each object in n2 carries 2 units of weight. So total weight is 2*n2.

Let, n2=2*n2;
and W=w1+w2;

So now, n2 and n1 are total weight available and W is the total weight capacity.

If W<=n2, it means we can fill all the weight in W by n2.

So, apply


ans+=W; //As W weight is available




else if(W>n2) // this means W can accommodate all n2 weight and will have spare space.






Do the exact same for n1 and print the value in ans.

p.s. In solving with n2, if W becomes 0, it doesn’t cause any problem with n1 part as we are adding and subtracting 0 from any value.

Easy to understand Solution

using namespace std;
#define ll unsigned long long
int main(){
    ll t, w1,w2,n1,n2,W;
        ll ans = 0;
        ll temp = min(w1/2+w2/2,n2);
        ans += min(w1+w2-2*temp, n1);
    return 0;