码迷,mamicode.com
首页 > 其他好文 > 详细

HackerRank - Knapsack

时间:2015-03-19 06:18:36      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

Very good problem to learn knapsack (complete knapsack in this case).

My brutal-force solution in Python got AC too, which surprised me a bit. Here is the ideal DP solution. Just check comments:

T = int(input())
for _ in range(0, T):
    n, k = map(int, input().strip().split())
    arr = [int(i) for i in input().strip().split()]

    dp = [0] * (k + 1)
    arr.sort()
    for g in range(1, k + 1):     # k slots in knapsack
        for i in range(0, n):    # for each candidate
            if arr[i] <= g:                
                # each item, cost == gain
                dp[g] = max(dp[g], arr[i] + dp[g - arr[i]])
    print (dp[k])

HackerRank - Knapsack

标签:

原文地址:http://www.cnblogs.com/tonix/p/4349273.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!