Minimize count of flips required to make sum of the given array equal to 0 | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 2001 ] [ 2001 ] ; int solve ( vector < int > & A , int i , int sum , int N ) { int res = 2001 ; if ( sum < 0 or ( i == N and sum != 0 ) ) { return 2001 ; } if ( sum == 0 or i >= N ) { return dp [ i ] [ sum ] = 0 ; } if ( dp [ i ] [ sum ] != -1 ) { return dp [ i ] [ sum ] ; } res = min ( solve ( A , i + 1 , sum - A [ i ] , N ) + 1 , solve ( A , i + 1 , sum , N ) ) ; return dp [ i ] [ sum ] = res ; } void minOp ( vector < int > & A , int N ) { int sum = 0 ; for ( auto it : A ) { sum += it ; } if ( sum % 2 == 0 ) { memset ( dp , -1 , sizeof ( dp ) ) ; int ans = solve ( A , 0 , sum / 2 , N ) ; if ( ans < 0 ans > N ) { cout << " - 1" << endl ; } else { cout << ans << endl ; } } else { cout << " - 1" << endl ; } } int main ( ) { vector < int > A = { 2 , 3 , 1 , 4 } ; int N = A . size ( ) ; minOp ( A , N ) ; return 0 ; }