Getting WA (MMPROD)

Can anyone help me to find the problem in my code for the question MMPROD

#include <iostream>
#include<vector>
#include <algorithm>

using namespace std;
int main() {
int test;
long long MOD = 1000000007;
cin >> test;
while(test--) {
    int n, k;
    cin >> n >> k;
    int a[n];
    vector<long long> pos, neg;
    for(int i = 0; i < n; i++) {
        cin >> a[i];
    }
    for(int i = 0; i < n; i++) {
        if(a[i] < 0)
            neg.push_back(-1 * a[i]);
        else
            pos.push_back(a[i]);
    }
    sort(neg.begin(), neg.end());
    sort(pos.begin(), pos.end());
    int l = neg.size();
    int r = pos.size();
    long long ans = 1;
    while(k >= 2 && (r >= 2 || l >= 2)) {
        if ((r - 2) <= 0 && ((k - 2) % 2) != 0 && l >= 2) {
            long long temp = ((neg[l - 1] * neg[l - 2])) % MOD;
            ans = (ans * temp) % MOD;
            l -= 2;
        } else if (l >= 2 && r >= 2) {
            long long temp1 = (neg[l - 1] * neg[l - 2]) % MOD;
            long long temp2 = (pos[r - 1] * pos[r - 2]) %MOD;
            if(temp1 >= temp2) {
                ans = (ans * temp1) % MOD;
                l -= 2;
            } else {
                ans = (ans * temp2) % MOD;
                r -= 2;
            }
        } else {
            if (l < 2) {
                long long temp = (pos[r - 1] * pos[r - 2]) % MOD;
                ans = (ans * temp) % MOD;
                r -= 2;
            } else {
                long long temp = (neg[l - 1] * neg[l - 2]) % MOD;
                ans = (ans * temp) % MOD;
                l -= 2;
            }
        }
        k -= 2;
    }
    if(k >= 1) {
        if(r != 0) {
            ans = (ans * pos[r - 1]) % MOD;
        } else {
            ans = (ans * (-1) * neg[0]) % MOD;
            if(ans < 0)
                ans += MOD;
        }
        k--;
    }
    cout << ans << endl;
}
return 0;
}

Still cannot find error??

what is your logic?

your_code_output
but it should be -6 (-1 * -2 * -3)

if there is no way you can make the overall product value positive then try to minimize the product value

1 Like

Thanks. I was doing multiplication two negative numbers for some iteration if they are bigger then multiplying ans with that product.
As your test case clearly finds the flaw in my logic.