Created
September 27, 2015 05:23
-
-
Save markroxor/d6960005ee9ac7a9cec9 to your computer and use it in GitHub Desktop.
Bottoms UP DP first https://www.hackerrank.com/challenges/unbounded-knapsack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sys import stdin | |
import dis | |
get = iter(map(int,stdin.read().split())).__next__ | |
def knapSack(lis,K,N): | |
dp = [[0]*(K+1)]*(N+1) | |
for n in range(N+1): | |
for k in range(K+1): | |
if (k==0): | |
dp[n][k] = 0 | |
elif (n==0): | |
dp[n][k] = 0 | |
elif k>=lis[n-1]: | |
dp[n][k] = max(lis[n-1]+dp[n][k-lis[n-1]],dp[n-1][k]) | |
else: | |
dp[n][k] = dp[n-1][k] | |
return dp[N][K] | |
def main(): | |
t = get() | |
for _ in range(t): | |
n = get() | |
k = get() | |
lis = [] | |
for _ in range(n): | |
lis.append(get()) | |
print (knapSack(lis,k,n)) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment