Rearrange array to make product of prefix sum array non zero | C ++ program to implement the above approach ; Function to print array elements ; Function to rearrange array that satisfies the given condition ; Stores sum of elements of the given array ; Calculate totalSum ; If the totalSum is equal to 0 ; No possible way to rearrange array ; If totalSum exceeds 0 ; Rearrange the array in descending order ; Otherwise ; Rearrange the array in ascending order ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << " ▁ " ; } } void rearrangeArr ( int arr [ ] , int N ) { int totalSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { totalSum += arr [ i ] ; } if ( totalSum == 0 ) { cout << " - 1" << endl ; } else if ( totalSum > 0 ) { sort ( arr , arr + N , greater < int > ( ) ) ; printArr ( arr , N ) ; } else { sort ( arr , arr + N ) ; printArr ( arr , N ) ; } } int main ( ) { int arr [ ] = { 1 , -1 , -2 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; rearrangeArr ( arr , N ) ; }