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 arrays are
and .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
Example:
Input: n = 4, a = [1,2,-1,4], b = [3,3,3,1]
Output: 1
Approach
C++
#include <bits/stdc++.h>using namespace std;void twoArrays(int n, int a[], int b[]){int sum1 = 0, sum2 = 0;int cnt1 = 0, cnt2 = 0;for (int i = 0; i < n; i++){sum1 += a[i];if (a[i] < 0)cnt1++;}for (int i = 0; i < n; i++){sum2 += b[i];if (b[i] < 0)cnt2++;}if (sum1 != sum2){if (sum1 > sum2 && cnt1 == 1 && cnt2 == 0)cout << "0\n";else if (sum2 > sum1 && cnt2 == 1 && cnt1 == 0)cout << "0\n";else if (sum1 > sum2 && cnt1 > 0 && cnt2 == 0)cout << "0\n";else if (sum2 > sum1 && cnt2 > 0 && cnt1 == 0)cout << "0\n";else if ((cnt1 == 0 && cnt2 == 2) ||cnt1 == 2 && cnt2 == 0)cout << abs(sum1 - sum2) - 1 << "\n";else if (cnt1 == cnt2)cout << "Infinite\n";elsecout << 1 << "\n";}else if ((cnt1 == 0 && cnt2 == 1) ||(cnt1 == 1 && cnt2 == 0))cout << 0 << "\n";elsecout << "Infinite\n";}int main(){int n = 4;int a[n] = {1, 2, -1, 4};int b[n] = {3, 3, 3, 1};twoArrays(n, a, b);return 0;}
No comments:
Post a Comment