Rearrange array to make product of prefix sum array non zero | Java 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
import java . util . * ; class GFG { static void printArr ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } static void rearrangeArr ( int arr [ ] , int N ) { int totalSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { totalSum += arr [ i ] ; } if ( totalSum == 0 ) { System . out . print ( " - 1" + "NEW_LINE"); } else if ( totalSum > 0 ) { Arrays . sort ( arr ) ; arr = reverse ( arr ) ; printArr ( arr , N ) ; } else { Arrays . sort ( arr ) ; printArr ( arr , N ) ; } } static int [ ] reverse ( int a [ ] ) { int i , n = a . length , t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } return a ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , - 1 , - 2 , 3 } ; int N = arr . length ; rearrangeArr ( arr , N ) ; } }