Queries to check whether all the elements can be made positive by flipping signs exactly K times | C ++ implementation of the approach ; To store the count of negative integers ; Check if zero exists ; Function to find the count of negative integers and check if zero exists in the array ; Function that returns true if array elements can be made positive by changing signs exactly k times ; Driver code ; Pre - processing ; Perform queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cnt_neg ; bool exists_zero ; void preProcess ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < 0 ) cnt_neg ++ ; if ( arr [ i ] == 0 ) exists_zero = true ; } } bool isPossible ( int k ) { if ( ! exists_zero ) { if ( k >= cnt_neg and ( k - cnt_neg ) % 2 == 0 ) return true ; else return false ; } else { if ( k >= cnt_neg ) return true ; else return false ; } } int main ( ) { int arr [ ] = { -1 , 2 , -3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( int ) ; preProcess ( arr , n ) ; int queries [ ] = { 1 , 2 , 3 , 4 } ; int q = sizeof ( queries ) / sizeof ( int ) ; for ( int i = 0 ; i < q ; i ++ ) { if ( isPossible ( queries [ i ] ) ) cout << " Yes " << endl ; else cout << " No " << endl ; } return 0 ; }