Divide array in two part such that sum of array left to partition index i is equal to sum of array right to partition index i.
That is A[0]+A[1]...+A[i-1]=A[i+1]+....+A[n]
This is slightly tricky question but very easy to solve and code ,if you find the trick.
That is A[0]+A[1]...+A[i-1]=A[i+1]+....+A[n]
This is slightly tricky question but very easy to solve and code ,if you find the trick.
Algorithm:
- Find the cumulative sum at each index of array
- loop through array and check A[i-1]==A[n]-A[i] , If condition Satisfy for any index i, means array can be partition in two group with this condition,So print "YES" else "NO"
- Use special case if array has only 1 element then print YES
- if array has only two element then print "NO"
C++ Source Code
- #include <cmath>
- #include <cstdio>
- #include <vector>
- #include <iostream>
- #include <algorithm>
- using namespace std;
- int main() {
- int n,key;
- vector<int> arr;
- cout<<"No of element in array:";
- cin>>n;
- cout<<"Enter Array data :";
- while(n--){
- cin>>key;
- arr.push_back(key);
- }
- //Special case for 1 and 2 element array
- if(arr.size()==1){
- cout<<"YES"<<endl;
- }
- else if(arr.size()==2){
- cout<<"NO"<<endl;
- }
- else{
- //find cumulative Sum at each index
- for(int i=1;i<arr.size();i++){
- arr[i]+=arr[i-1];
- }
- int flag=0;
- n=arr.size()-1;
- //check is arr[i-1]==arr[n]-arr[i]
- for(int i=1;i<n;i++){
- if(arr[i-1]==(arr[n]-arr[i])){
- flag=1;
- break;
- }
- }
- if(flag)
- cout<<"YES"<<endl;
- else
- cout<<"NO"<<endl;
- }
- return 0;
- }
No comments:
Post a Comment
THANKS FOR UR GREAT COMMENT