Given an array[ ] size N and consists of positive and negative one’s. Given M queries and each query consists of left (Li) and right (Ri) index. The task is to rearranged the elements of array[ ] then the Ali + Ali+1 + …. + Ari = 0 sum is zero. If this is possible print true else false. where (Li <= Ri <= N).
Examples :
Input :
N = 5
array[ ] = { 1 , 1 , -1 , 1 , -1 }
M = 4
1 1
2 3
1 5
1 4
Output :
False
True
False
True
Explanation :
In 1st query, we can't rearranged any 1 element , sum is 1 or -1.
In 2nd query, we rearranged 2 elements of array 1 and -1 so, the sum
is 0.
In 3rd query, sum of index 1 to 5 is 1 + 1 + (-1) + 1 + (-1) Sum is
1.
In 4th query we can rearranged 1 + (-1) + (-1) + 1 then the sum is 0.
Input :
N = 3
array[ ] = { 1 , -1 , 1 }
M = 2
1 3
1 2
Output :
False
True
Explanation :
In 1st query, we can't rearranged any 3 elements sum is 1 + (-1) + 1
= 1.
In 2nd query, we rearranged 2 elements of array 1 and -1 so, the sum
is 0.
Approach :
- Make two variables positive and negative which store the count of -1’s and +1’s .
- Iterate the array[ ] and increment positive and negative variable according to their type.
- Now, Check each query and make variable temp and store the difference b/w Li and Ri.
- If temp+1 is odd print False. Because we can’t rearranged the odd number of elements so their sum is zero.
- Else we want (temp+1)/2 positive +1’s and negative -1’s to make valid array so that their sum is zero.
- If it array contains that much +1’s and -1’s print True, Else we print False.
Implementation :
#include<iostream>
using namespace std;
bool PossibleArray(int arr[], int N, int Li, int Ri){
//make two variables positive and negative
//which store -1's and +1's
int posOnes = 0, negOnes = 0;
for(int i = 0; i < N; i++){
//if element is postive 1
if(arr[i] == 1){
posOnes++;
}
//if element is -1
else{
negOnes++;
}
}
//store the diffrence
int diff = Ri - Li + 1;
//if diff is odd
//not possible to make a valid array
if(diff & 1){
return false;
}
//if diff is even
//check for avalaibility of 1's and -1's
//if we have diff/2 pos and neg ones return true
if(posOnes >= diff/2 and negOnes >= diff/2){
return true;
}
//if above condition are not satisfy return false
return false;
}
int main(){
int arr[] = { 1 , -1 , 1 , -1 , 1 };
//size of array
int N = sizeof(arr)/sizeof(int);
//queries
int M = 2;
int Li = 1, Ri = 4;
//call the function
bool isPossible = PossibleArray(arr, N, Li, Ri);
//is it is true
if(isPossible){
cout << "True\n";
}
else{
cout << "False\n";
}
//check for next query
Li = 3 , Ri = 5;
isPossible = PossibleArray(arr, N, Li, Ri);
if(isPossible){
cout << "True";
}
else{
cout << "False";
}
}
Time Complexity : O(N)