0 | Python3 implementation of the approach ; To store states of DP ; To check if a state has been solved ; Function to compute the states ; Base case ; Check if a state has been solved ; Setting a state as solved ; Returning the solved state ; Function to pre - compute the states dp [ 0 ] [ 0 ] , dp [ 0 ] [ 1 ] , . . , dp [ 0 ] [ C_MAX ] ; Function to answer a query in O ( 1 ) ; Driver code ; Performing required pre - computation ; Perform queries
import numpy as np NEW_LINE import sys NEW_LINE C_MAX = 30 NEW_LINE max_arr_len = 10 NEW_LINE dp = np . zeros ( ( max_arr_len , C_MAX + 1 ) ) ; NEW_LINE v = np . zeros ( ( max_arr_len , C_MAX + 1 ) ) ; NEW_LINE INT_MIN = - ( sys . maxsize ) + 1 NEW_LINE def findMax ( i , r , w , n ) : NEW_LINE INDENT if ( r < 0 ) : NEW_LINE INDENT return INT_MIN ; NEW_LINE DEDENT if ( i == n ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( v [ i ] [ r ] ) : NEW_LINE INDENT return dp [ i ] [ r ] ; NEW_LINE DEDENT v [ i ] [ r ] = 1 ; NEW_LINE dp [ i ] [ r ] = max ( w [ i ] + findMax ( i + 1 , r - w [ i ] , w , n ) , findMax ( i + 1 , r , w , n ) ) ; NEW_LINE return dp [ i ] [ r ] ; NEW_LINE DEDENT def preCompute ( w , n ) : NEW_LINE INDENT for i in range ( C_MAX , - 1 , - 1 ) : NEW_LINE INDENT findMax ( 0 , i , w , n ) ; NEW_LINE DEDENT DEDENT def ansQuery ( w ) : NEW_LINE INDENT return dp [ 0 ] [ w ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT w = [ 3 , 8 , 9 ] ; NEW_LINE n = len ( w ) NEW_LINE preCompute ( w , n ) ; NEW_LINE queries = [ 11 , 10 , 4 ] ; NEW_LINE q = len ( queries ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT print ( ansQuery ( queries [ i ] ) ) ; NEW_LINE DEDENT DEDENT