Rearrange given array to obtain positive prefix sums at exactly X indices | C ++ program for the above approach ; Function to rearrange the array according to the given condition ; Using 2 nd operation making all values positive ; Sort the array ; Assign K = N - K ; Count number of zeros ; If number of zeros if greater ; Using 2 nd operation convert it into one negative ; Using 2 nd operation convert it into one negative ; Print the array ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void rearrange ( int * a , int n , int x ) { for ( int i = 0 ; i < n ; i ++ ) a [ i ] = abs ( a [ i ] ) ; sort ( a , a + n ) ; x = n - x ; int z = count ( a , a + n , 0 ) ; if ( x > n - z ) { cout << " - 1 STRNEWLINE " ; return ; } for ( int i = 0 ; i < n && x > 0 ; i += 2 ) { a [ i ] = - a [ i ] ; x -- ; } for ( int i = n - 1 ; i >= 0 && x > 0 ; i -- ) { if ( a [ i ] > 0 ) { a [ i ] = - a [ i ] ; x -- ; } } for ( int i = 0 ; i < n ; i ++ ) { cout << a [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 0 , -2 , 4 , 5 , -3 } ; int K = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; rearrange ( arr , N , K ) ; return 0 ; }