Minimize count of flips required to make sum of the given array equal to 0 | Java program for the above approach ; Initialize dp [ ] [ ] ; Function to find the minimum number of operations to make sum of A [ ] 0 ; Initialize answer ; Base case ; Otherwise , return 0 ; Pre - computed subproblem ; Recurrence relation for finding the minimum of the sum of subsets ; Return the result ; Function to find the minimum number of elements required to be flipped to amke sum the array equal to 0 ; Find the sum of array ; Initialise dp [ ] [ ] with - 1 ; No solution exists ; Otherwise ; If sum is odd , no subset is possible ; Driver Code ; Function Call
class GFG { static int [ ] [ ] dp = new int [ 2001 ] [ 2001 ] ; static int solve ( int [ ] A , int i , int sum , int N ) { int res = 2001 ; if ( sum < 0 || ( i == N && sum != 0 ) ) { return 2001 ; } if ( sum == 0 i >= N ) { return dp [ i ] [ sum ] = 0 ; } if ( dp [ i ] [ sum ] != - 1 ) { return dp [ i ] [ sum ] ; } res = Math . min ( solve ( A , i + 1 , sum - A [ i ] , N ) + 1 , solve ( A , i + 1 , sum , N ) ) ; return dp [ i ] [ sum ] = res ; } static void minOp ( int [ ] A , int N ) { int sum = 0 ; for ( int it : A ) { sum += it ; } if ( sum % 2 == 0 ) { for ( int i = 0 ; i < 2001 ; i ++ ) { for ( int j = 0 ; j < 2001 ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } int ans = solve ( A , 0 , sum / 2 , N ) ; if ( ans < 0 ans > N ) { System . out . print ( " - 1" + "NEW_LINE"); } else { System . out . print ( ans + "NEW_LINE"); } } else { System . out . print ( " - 1" + "NEW_LINE"); } } public static void main ( String [ ] args ) { int [ ] A = { 2 , 3 , 1 , 4 } ; int N = A . length ; minOp ( A , N ) ; } }