Backpack with Value array:
note that now you can take k times, or "infinite times"
function:
dp[i][j] = Math.max(dp[i - 1][j - A[i - 1] * k] + V[i - 1] * k, dp[i][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 A: an integer array | |
* @param V: an integer array | |
* @param m: An integer | |
* @return: an array | |
*/ | |
public int backPackIII(int[] A, int[] V, int m) { | |
// 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++) { | |
dp[i][j] = dp[i - 1][j]; | |
int k = 1; | |
while (j - A[i-1] * k >= 0) { | |
dp[i][j] = Math.max(dp[i - 1][j - A[i - 1] * k] + V[i - 1] * k, dp[i][j]); | |
k++; | |
} | |
} | |
} | |
// dp: answer | |
return dp[n][m]; | |
} | |
} |
No comments:
Post a Comment