你总共有n
元,商人总共有三种商品,它们的价格分别是150元,250元,350元,三种商品的数量可以认为是无限多的,购买完商品以后需要将剩下的钱给商人作为小费,求最少
需要给商人多少小费
样例
Example 1:
Input: n = 900
Output: 0
Example 2:
Input: 800
Output: 50
解题思路:
完全背包问题,解决方法与01背包的区别是,将从后向前遍历改为从前向后遍历,因为从前向后遍历会暂存前一个此元素保存进背包的值,而从后向前就会覆盖。
public class Solution {
/**
* @param n: the money you have
* @return: the minimum money you have to give
*/
public int backPackX(int n) {
// write your code here
int[] coins = {150, 250, 350};
int[] dp = new int[n+1];
for(int i=0; i<coins.length; i++)
for(int j=coins[i]; j<=n; j++)
dp[j] = Math.max(dp[j], dp[j-coins[i]] + coins[i]);
return n - dp[n];
}
}