
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Split Array with Same Average in C++
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 −
- n := size of A, total := 0
- for initialize i := 0, when i < n, update (increase i by 1), do −
- total := total + A[i]
- isPossible := false, m := n / 2
- for initialize i := 1, when i <= m and not isPossible is non-zero, update (increase i by 1), do −
- if total * i mod n is same as 0, then −
- isPossible := true
- if total * i mod n is same as 0, then −
- if not isPossible is non-zero, then −
- return false
- Define one 2D array dp of size (total + 1) x (n / 2) + 1)
- dp[0, 0] := true
- for initialize i := 0, when i < n, update (increase i by 1), do −
- x := A[i]
- for initialize j := total, when j >= x, update (decrease j by 1), do −
- for initialize l := 1, when l <= (n / 2), update (increase l by 1), do −
- dp[j, l] := dp[j, l] OR dp[j - x, l - 1]
- for initialize l := 1, when l <= (n / 2), update (increase l by 1), do −
- for initialize i := 1, when i <= (n / 2), update (increase i by 1), do −
- if (total * i) mod n is same as 0 and dp[total * i / n, i] is non-zero, then −
- return true
- if (total * i) mod n is same as 0 and dp[total * i / n, i] is non-zero, then −
- return false
Let us see the following implementation to get better understanding −
Example
#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)); }
Input
{1,2,3,4,5,6,7,8,9,10}
Output
1
Advertisements