Need help in troubleshooting my MAXAND solution

My code kept giving WA / RA and I am not quite sure why. It clears the sample as well as self made testcases too.

void decToBinary(ll n, ll bitKeep[MAX]) { 
    ll i = 0; 
    while (n > 0) { 
        if(n & 1)
            bitKeep[i]++;
        n /= 2; 
        i++; 
    }
} 

int main() {
    fastIO;
    ll t; cin >> t;
    for(ll q = 0; q < t; q++) {
        ll bitKeep[MAX] = {0};
        ll n, k; cin >> n >> k;
        ll a[n];
        for(ll i = 0; i < n; i++) {
            cin >> a[i];
            decToBinary(a[i], bitKeep);
        }
        vpll vals;
        for(ll i = 0; i < MAX; i++) {
            if(bitKeep[i])
                vals.pb(mp(bitKeep[i] * (1<<i), i));
        }
        sort(vals.rbegin(), vals.rend());
        ll ansArr[MAX] = {0};
        for(ll i = 0, x = 0; i < MAX && x < k; i++, x++)
            ansArr[vals[i].second] = 1;
        ll ans = 0;
        for(ll i = 0; i < MAX; i++)
            if(ansArr[i])
                ans += (1<<i);
        cout << ans << endl;
    }
    return 0;
}

For those who might want to see the submission : here

Thanks in advanced.

Why do you have line 46

It was to avoid pushing the pairs which weren’t ON even for a single time. I think that was avoidable.

i see your code is adding potential bits as much as needed, but what if k > the bits required, you would have to add least significant possible bits for that

for following input :
1
4 4
1 3 4 5

your codes output is 7 : 0111
but we need 4 bits so output should have been 1111 = 15.

1 Like

Another thing: you need to correctly handle the situation where there are ties, as in, multiple bits where adding them would give the same value.

1 Like

Oh, now I see that. Thanks for pointing out! :slight_smile:

Yes, silly mistake from my end, thanks for helping! :slight_smile: