Fill dp [ ] [ ] in bottom up manner ( Similar to knapsack ) .
for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , x + 1 ) : NEW_LINE INDENT if a [ i ] <= j : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i - 1 ] [ j ] , a [ i ] + dp [ i - 1 ] [ j - a [ i ] ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT DEDENT