Rearrange given array to obtain positive prefix sums at exactly X indices | Java 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
import java . util . * ; class GFG { static int count ( int [ ] a ) { int counter = 0 ; for ( int i = 0 ; i < a . length ; i ++ ) { if ( a [ i ] == 0 ) { counter ++ ; } } return counter ; } static void rearrange ( int [ ] a , int n , int x ) { for ( int i = 0 ; i < n ; i ++ ) a [ i ] = Math . abs ( a [ i ] ) ; Arrays . sort ( a ) ; x = n - x ; int z = count ( a ) ; if ( x > n - z ) { System . out . println ( " - 1" ) ; 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 ++ ) { System . out . print ( a [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 0 , - 2 , 4 , 5 , - 3 } ; int K = 3 ; int N = arr . length ; rearrange ( arr , N , K ) ; } }