算法学习记录——挖金矿求最佳收益问题(JAVA实现)
//挖金矿求最佳收益问题
/*
* 算法核心思想--->动态规划问题:
* 1、确定最优子结构
* 2、确定全局最优解
* 3、确定最优子结构与全局最优解之间的关系
* 4、确定问题边界
*/
/*
* 本题的具体解法分析:
* 金矿数---> n(本题中用 g.length 表示)
* 工人数---> w
* 每个金矿的含金量数组---> g[]
* 每个金矿所需挖矿工人数---> p[]
* F(n,w) ---> n个金矿,w个工人时的最佳收益函数
*
* =========================================
* 本题的转化函数式:
* F(n,w)=0 (n=0 或者 w=0)
* F(n,w)=F(n-1,w) (n>=1, w<p[n-1])
* F(n,w)=Math.max(F(n-1,w), F(n-1, w-p[n-1])+g[n-1]) (n>=1, w>=p[n-1])
*
*
*/
public class BestGoldMining {
public static int getBestGoldMining(int w, int[] p, int[] g) {
int[][] result=new int[g.length+1][w+1];
for(int i=1; i<=g.length; i++) {
for(int j=1; j<=w; j++) {
if(j<p[i-1]) {
result[i][j]=result[i-1][j];
}
else
{
result[i][j]=Math.max(result[i-1][j], result[i-1][j-p[i-1]]+g[i-1]);
}
}
}
return result[g.length][w];
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int w = 10;
int[] p = {5, 5, 3, 4 ,3};
int[] g = {400, 500, 200, 300 ,350};
System.out.println(" 最优收益:" + getBestGoldMining(w, p, g));
}
}