Required sum is minimum non - negative So , we iterate from i = 0 to sum and find the first i where dp [ flag ^ 1 ] [ i ] != INT_MAX
for ( int i = 0 ; i <= sum ; i ++ ) { if ( dp [ flag ^ 1 ] [ i ] != INT_MAX ) return dp [ flag ^ 1 ] [ i ] ; }