We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
defunboundedKnapsack(k,arr):# progressively get responses (DP)# k 0 1 2 3 4 5 6# 0 0 0 0 0 0 0 0 # 2 0 0 2 2 4 4 6 dp[i][j] = max(dp[i-1][j], dp[i][j-i]+i)# 3 0 0 2 3 4 5 6 (choosing between not adding anything and# 4 0 0 2 3 4 5 6 adding the current N's value to the Nth# value behind)# stop searching if k is found. If not, return largest.# Creating dp tabledp=[[0for_inrange(0,k+1)]for_inrange(0,len(arr)+1)]options=[0]+arrnum_ints=len(arr)max_val=0foriinrange(1,num_ints+1):forjinrange(1,k+1):ifj<options[i]:# is the current k less than the value of the line?dp[i][j]=dp[i-1][j]else:dp[i][j]=max(dp[i-1][j],dp[i][j-options[i]]+options[i])ifdp[i][j]==k:# found k in DP tablereturnkmax_val=max(max_val,dp[i][j])j+=1i+=1# k is not on DP table, so returning max value foundreturnmax_val
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Knapsack
You are viewing a single comment's thread. Return to all comments →
Python: you need to FIX THE MAIN!
It should be:
Resolution: