Maximize Array sum after changing sign of any elements for exactly M times | C # implementation of the above approach ; 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 ; Driver Code ; Given input
using System ; using System . Collections . Generic ; public class GFG { static void findMaximumSumWithMflips ( int [ ] arr , int N , int M ) { List < int > minHeap = new List < int > ( ) ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { minHeap . Add ( arr [ i ] ) ; sum += arr [ i ] ; } minHeap . Sort ( ) ; while ( M -- > 0 ) { sum -= minHeap [ 0 ] ; int temp = - 1 * minHeap [ 0 ] ; minHeap . RemoveAt ( 0 ) ; sum += temp ; minHeap . Add ( temp ) ; minHeap . Sort ( ) ; } Console . WriteLine ( sum ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { - 3 , 7 , - 1 , - 5 , - 3 } ; int M = 4 , N = 5 ; findMaximumSumWithMflips ( arr , N , M ) ; } }