Rearrange given array to obtain positive prefix sums at exactly X indices | Javascript 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 function ; Function Call
function count ( a ) { let counter = 0 ; for ( let i = 0 ; i < a . length ; i ++ ) { if ( a [ i ] == 0 ) { counter ++ ; } } return counter ; } function rearrange ( a , n , x ) { for ( let i = 0 ; i < n ; i ++ ) a [ i ] = Math . abs ( a [ i ] ) ; a . sort ( ) ; x = n - x ; let z = count ( a ) ; if ( x > n - z ) { document . write ( " " ) ; return ; } for ( let i = 0 ; i < n && x > 0 ; i += 2 ) { a [ i ] = - a [ i ] ; x -- ; } for ( let i = n - 1 ; i >= 0 && x > 0 ; i -- ) { if ( a [ i ] > 0 ) { a [ i ] = - a [ i ] ; x -- ; } } for ( let i = 0 ; i < n ; i ++ ) { document . write ( a [ i ] + " " ) ; } } let arr = [ 0 , - 2 , 4 , 5 , - 3 ] ; let K = 3 ; let N = arr . length ; rearrange ( arr , N , K ) ;