In this HackerEarth 2 arrays problem solution you are given 2 arrays A and B, each of the size N. Each element of these arrays is either a positive integer or -1. The total number of -1's that can appear over these 2 arrays are >= 1 and <= 2.

Now, you need to find the number of ways in which we can replace each -1 with a non-negative integer, such that the sum of both of these arrays is equal.


HackerEarth 2 arrays problem solution


HackerEarth 2 arrays problem solution.

#include<bits/stdc++.h>

using namespace std;

typedef complex<double> base;
typedef long double ld;
typedef long long ll;

#define pb push_back
#define pii pair<int,int>
#define vi vector<int>

const int maxn=(int)(1e5+5);
const ll mod=(ll)(998244353);
int a[maxn],b[maxn];

int main()
{
    ios_base::sync_with_stdio(0);

    int n,ctr=0;cin>>n;

    ll sum1=0,sum2=0;

    bool a_q=false,b_q=false;

    for(int i=0;i<n;i++)
    {
        cin>>a[i];

        if(a[i]==-1)
        {
            a_q=true;

            ctr++;
        }

        else
        {
            sum1+=a[i];
        }
    }

    for(int i=0;i<n;i++)
    {
        cin>>b[i];

        if(b[i]==-1)
        {
            ctr++;

            b_q=true;
        }

        else
        {
            sum2+=b[i];
        }
    }

    if(ctr==1)
    {
        ll now=(a_q?(sum2-sum1):(sum1-sum2));

        if(now>=0)
        {
            cout<<1<<endl;
        }
        else
        {
            cout<<0<<endl;
        }
    }

    else
    {
        if(a_q && b_q)
        {
            cout<<"Infinite"<<endl;
        }

        else
        {
           ll now=(a_q?sum2-sum1:sum1-sum2);

           if(now>=0)
           {
               cout<<(now+1)<<endl;
           }

           else
           {
               cout<<0<<endl;
           }
        }
    }

    return 0;
}

Second solution

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 14;

int n, m, c[2];
int s[2];
int main(){
    ios::sync_with_stdio(0), cin.tie(0);
    cin >> n;
    for(int k = 0; k < 2; k++)
        for(int i = 0; i < n; i++){
            int x;
            cin >> x;
            if(x == -1)
                c[k]++;
            else
                s[k] += x;
        }
    if(c[0] && c[1])
        return cout << "Infinite\n", 0;
    if(!c[0]){
        swap(c[0], c[1]);
        swap(s[0], s[1]);
    }
    if(s[0] > s[1])
        cout << "0\n";
    else if(c[0] == 1)
        cout << 1 << '\n';
    else
        cout << s[1] - s[0] + 1 << '\n';
    
}