Java 贪心算法实现:最大价值计算
public class GreedyAlgorithm {
public static void main(String[] args) {
int[] arr = {6, 3, 2, 4, 5};
int target = 10;
int result = greedy(arr, target);
System.out.println('最大价值为:' + result);
}
public static int greedy(int[] arr, int target) {
Arrays.sort(arr);//将数组从小到大排序
int sum = 0;//初始化价值为0
for (int i = arr.length - 1; i >= 0; i--) {//从最大值开始往前遍历
if (arr[i] <= target) {//如果当前值小于等于目标值
sum += arr[i];//将当前值加入到价值中
target -= arr[i];//将目标值减去当前值
}
}
return sum;//返回最大价值
}
}
原文地址: https://www.cveoy.top/t/topic/mzF1 著作权归作者所有。请勿转载和采集!