LinCode - Backpack IIFollow
Description
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?
You cannot divide item into small pieces and the total size of items you choose should smaller or equal to m.
Have you met this question in a real interview? Yes
Problem Correction
Example
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
.
Analyst
最后一步
F[n][m]
表示前n
个背包放入了重量m
的value
最后一个背包
A[n-1]
能被放入:F[n][m] = F[n-1][m-A[n-1]] + B[n-1]
最后一个背包
A[n-1]
不能被放入:F[n][m] = F[n-1][m]
顺序:由小到大
边界情况:
前0个放入任意重量
F[0][m] = Integer.MIN_VALUE
状态方程:
F[n][m] = Math.max(F[n-1][m] ,F[n-1][m-A[n-1]] + B[n-1])
Code
1 | public class Solution { |