Maximize array sum after K negations | Set 1 | Java program for the above approach ; Function to calculate sum of the array ; Iterate from 0 to n - 1 ; Function to maximize sum ; Iterate from 0 to n - 1 ; Driver Code ; Function Call
import java . util . * ; class GFG { static int sumArray ( int [ ] arr , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } return sum ; } static int maximizeSum ( int arr [ ] , int n , int k ) { Arrays . sort ( arr ) ; int i = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( k != 0 && arr [ i ] < 0 ) { arr [ i ] *= - 1 ; k -- ; continue ; } break ; } if ( i == n ) i -- ; if ( k == 0 k % 2 == 0 ) { return sumArray ( arr , n ) ; } if ( i != 0 && Math . abs ( arr [ i ] ) >= Math . abs ( arr [ i - 1 ] ) ) { i -- ; } arr [ i ] *= - 1 ; return sumArray ( arr , n ) ; } public static void main ( String args [ ] ) { int n = 5 ; int k = 4 ; int arr [ ] = { - 3 , - 2 , - 1 , 5 , 6 } ; System . out . print ( maximizeSum ( arr , n , k ) ) ; } }