Maximize Array sum after changing sign of any elements for exactly M times | Function to find the maximum sum with M flips ; Declare a priority queue i . e . min heap ; Declare the sum as zero ; Push all elements of the array in it ; Iterate for M times ; Get the top element ; Flip the sign of the top element ; Remove the top element ; Update the sum ; Push the temp into the queue ; Given input
function findMaximumSumWithMflips ( arr , N , M ) { let pq = [ ] let sum = 0 for ( let i = 0 ; i < N ; i ++ ) { pq . push ( arr [ i ] ) sum += arr [ i ] pq . sort ( ( a , b ) => a - b ) } while ( M > 0 ) { sum -= pq [ 0 ] temp = - 1 * pq [ 0 ] pq . shift ( ) sum += temp pq . push ( temp ) pq . sort ( ( a , b ) => a - b ) M -= 1 } document . write ( sum ) } let arr = [ - 3 , 7 , - 1 , - 5 , - 3 ] let N = arr . length let M = 4 findMaximumSumWithMflips ( arr , N , M )