Rearrange given array to obtain positive prefix sums at exactly X indices | 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 array ; Driver Code ; Function Call
def rearrange ( a , n , x ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT a [ i ] = abs ( a [ i ] ) NEW_LINE DEDENT a = sorted ( a ) NEW_LINE x = n - x ; NEW_LINE z = a . count ( 0 ) NEW_LINE if ( x > n - z ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT for i in range ( 0 , n , 2 ) : NEW_LINE INDENT if x <= 0 : NEW_LINE INDENT break NEW_LINE DEDENT a [ i ] = - a [ i ] NEW_LINE x -= 1 NEW_LINE DEDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if x <= 0 : NEW_LINE INDENT break NEW_LINE DEDENT if ( a [ i ] > 0 ) : NEW_LINE INDENT a [ i ] = - a [ i ] NEW_LINE x -= 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , - 2 , 4 , 5 , - 3 ] NEW_LINE K = 3 NEW_LINE N = len ( arr ) NEW_LINE rearrange ( arr , N , K ) NEW_LINE DEDENT