Maximize the sum of array by multiplying prefix of array with | Javascript implementation of the above approach ; To store sum ; To store ending indices of the chosen prefix array vect ; Adding the absolute value of a [ i ] ; If i == 0 then there is no index to be flipped in ( i - 1 ) position ; print the maximised sum ; print the ending indices of the chosen prefix arrays ; driver code
function maxSum ( a , n ) { let l = [ ] ; let s = 0 ; for ( let i = 0 ; i < n ; i ++ ) { s += Math . abs ( a [ i ] ) ; if ( a [ i ] >= 0 ) continue ; if ( i == 0 ) l . push ( i + 1 ) ; else { l . push ( i + 1 ) ; l . push ( i ) ; } } document . write ( s + " " ) ; for ( let i = 0 ; i < l . length ; i ++ ) document . write ( l [ i ] + " " ) ; } let n = 4 ; let a = [ 1 , - 2 , - 3 , 4 ] ; maxSum ( a , n ) ;