Find maximum sum of subsequence after flipping signs of at most K elements in given Array | C ++ implementation for the above approach ; 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 ; Driver Code ; Given array ; Variable to store number of flips are allowed ; Function call to find the maximum sum of subsequence
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSubseq ( int arr [ ] , int N , int K ) { int sum = 0 ; sort ( arr , arr + N ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( K == 0 ) break ; if ( arr [ i ] < 0 ) { arr [ i ] = - arr [ i ] ; K -- ; } } for ( int i = 0 ; i < N ; i ++ ) if ( arr [ i ] > 0 ) sum += arr [ i ] ; return sum ; } int main ( ) { int arr [ ] = { 6 , -10 , -1 , 0 , -4 , 2 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxSubseq ( arr , N , K ) ; return 0 ; }