lintcode-medium-Backpack II

Given n items with size Ai and value Vi, and a backpack with size m. What's the maximum value can you put into the backpack?

Given 4 items with size [2, 3, 5, 7] and value [1, 5, 2, 4], and a backpack with size 10. The maximum value is 9.

 

和上一题差不多,这题里动态规划用的数组类型是int[],用来记录背包里放容积为k的物体时,这些物体的最大价值

public class Solution {
    /**
     * @param m: An integer m denotes the size of a backpack
     * @param A & V: Given n items with size A[i] and value V[i]
     * @return: The maximum value
     */
    public int backPackII(int m, int[] A, int V[]) {
        // write your code here
        
        if(A == null || A.length == 0)
            return 0;
        
        int[] dp = new int[m + 1];
        int result = 0;
        
        dp[0] = 0;
        
        for(int i = 0; i < A.length; i++){
            for(int j = m ; j >= A[i]; j--){
                dp[j] = Math.max(dp[j], dp[j - A[i]] + V[i]);
            }
        }
        
        for(int i = 0; i < dp.length; i++){
            if(dp[i] > result)
                result = dp[i];
        }
        return result;
    }
}

 

posted @ 2016-03-14 15:00  哥布林工程师  阅读(179)  评论(0编辑  收藏  举报