Find maximum subset sum formed by partitioning any subset of array into 2 partitions with equal sum | Python3 implementation for the above mentioned Dynamic Programming approach ; Function to find the maximum subset sum ; sum of all elements ; bottom up lookup table ; ; initialising dp table with INT_MIN where , INT_MIN means no solution ; Case when diff is 0 ; Putting ith element in g0 ; Putting ith element in g1 ; Ignoring ith element ; Driver code
import numpy as np NEW_LINE import sys NEW_LINE INT_MIN = - ( sys . maxsize - 1 ) NEW_LINE def maxSum ( a , n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += a [ i ] ; NEW_LINE DEDENT limit = 2 * sum + 1 ; NEW_LINE dp = np . zeros ( ( n + 1 , limit ) ) ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( limit ) : NEW_LINE INDENT dp [ i ] [ j ] = INT_MIN ; NEW_LINE DEDENT DEDENT dp [ 0 ] [ sum ] = 0 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( limit ) : NEW_LINE INDENT if ( ( j - a [ i - 1 ] ) >= 0 and dp [ i - 1 ] [ j - a [ i - 1 ] ] != INT_MIN ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i - 1 ] [ j - a [ i - 1 ] ] + a [ i - 1 ] ) ; NEW_LINE DEDENT if ( ( j + a [ i - 1 ] ) < limit and dp [ i - 1 ] [ j + a [ i - 1 ] ] != INT_MIN ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i - 1 ] [ j + a [ i - 1 ] ] ) ; NEW_LINE DEDENT if ( dp [ i - 1 ] [ j ] != INT_MIN ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i - 1 ] [ j ] ) ; NEW_LINE DEDENT DEDENT DEDENT return dp [ n ] [ sum ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 ; NEW_LINE a = [ 1 , 2 , 3 , 6 ] ; NEW_LINE print ( maxSum ( a , n ) ) ; NEW_LINE DEDENT