Maximize sum of an Array by flipping sign of all elements of a single subarray | Java program for the above approach ; Function to find the maximum sum after flipping a subarray ; Stores the total sum of array ; Initialize the maximum sum ; Iterate over all possible subarrays ; Initialize sum of the subarray before flipping sign ; Initialize sum of subarray after flipping sign ; Calculate the sum of original subarray ; Subtract the original subarray sum and add the flipped subarray sum to the total sum ; Return the max_sum ; Driver Code ; Function call
import java . io . * ; public class GFG { public static int maxSumFlip ( int a [ ] , int n ) { int total_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) total_sum += a [ i ] ; int max_sum = Integer . MIN_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; int flip_sum = 0 ; for ( int j = i ; j < n ; j ++ ) { sum += a [ j ] ; max_sum = Math . max ( max_sum , total_sum - 2 * sum ) ; } } return Math . max ( max_sum , total_sum ) ; } public static void main ( String args [ ] ) { int arr [ ] = { - 2 , 3 , - 1 , - 4 , - 2 } ; int N = arr . length ; System . out . println ( maxSumFlip ( arr , N ) ) ; } }