Backpack with Value array:
function:
dp[i][j] = Math.max(dp[i - 1][j - A[i - 1]] + V[i - 1], dp[i - 1][j]); (when you take that ith item)
or
dp[i][j] += dp[i - 1][j]; (when you don't take that ith item)
This file contains 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
public class Solution { | |
/** | |
* @param m: An integer m denotes the size of a backpack | |
* @param A: Given n items with size A[i] | |
* @param V: Given n items with 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 n = A.length; | |
// init | |
int[][] dp = new int[n+1][m+1]; | |
dp[0][0] = 0; | |
for (int j = 1; j <= m; j++) { | |
dp[0][j] = 0; | |
} | |
// dp: functions | |
int maximumJ = Integer.MIN_VALUE; | |
for (int i = 1; i <= n; i++) { | |
dp[i][0] = 0; | |
for (int j = 1; j <= m; j++) { | |
if (j - A[i-1] >= 0) { | |
dp[i][j] = Math.max(dp[i - 1][j - A[i - 1]] + V[i - 1], dp[i - 1][j]); | |
} else { | |
dp[i][j] += dp[i - 1][j]; | |
} | |
} | |
} | |
// dp: answer | |
return dp[n][m]; | |
} | |
} |
No comments:
Post a Comment