Find maximum sum of subsequence after flipping signs of at most K elements in given Array | Function to calculate the max sum of subsequence ; Variable to store the max sum ; Sort the array ; Iterate over the array ; Flip sign ; Decrement k ; Traverse over the array ; Add only positive elements ; Return the max sum ; Given array ; Variable to store number of flips are allowed ; Function call to find the maximum sum of subsequence
const maxSubseq = ( arr , N , K ) => { let sum = 0 ; arr . sort ( ( a , b ) => a - b ) ; for ( let i = 0 ; i < N ; i ++ ) { if ( K == 0 ) break ; if ( arr [ i ] < 0 ) { arr [ i ] = - arr [ i ] ; K -- ; } } for ( let i = 0 ; i < N ; i ++ ) if ( arr [ i ] > 0 ) sum += arr [ i ] ; return sum ; } let arr = [ 6 , - 10 , - 1 , 0 , - 4 , 2 ] ; let K = 2 ; let N = arr . length document . write ( maxSubseq ( arr , N , K ) ) ;