Suppose we have one array A, we must move every element of A to either list B or list C. (These lists B and C are initially empty.) We have to check whether after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
So if the input is like − [1,2,3,4,5,6,7,8,9,10], then the result will be true,
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: bool splitArraySameAverage(vector<int>& A) { int n = A.size(); int total = 0 ; for(int i = 0; i < n; i++) total += A[i]; bool isPossible = false; int m = n / 2; for (int i = 1; i <= m && !isPossible; ++i) if (total*i%n == 0) isPossible = true; if (!isPossible) return false; vector < vector <bool> > dp(total + 1, vector <bool>((n / 2) + 1)); dp[0][0] = true; for(int i = 0; i < n; i++){ int x = A[i]; for(int j = total; j >= x; j--){ for(int l = 1; l <= (n / 2); l++){ dp[j][l] = dp[j][l] || dp[j - x][l - 1]; } } } for(int i = 1 ; i <= (n / 2); i++){ if((total * i) % n == 0 && dp[total * i / n][i]) return true; } return false; } }; main(){ Solution ob; vector<int> v = {1,2,3,4,5,6,7,8,9,10}; cout << (ob.splitArraySameAverage(v)); }
{1,2,3,4,5,6,7,8,9,10}
1