贪心算法(Greedy Algorithm)是一种常见的算法设计策略,通常用于解决一类优化问题。其核心思想是:在每一步选择中都采取当前状态下的最优决策,从而希望最终能够达到全局最优解。贪心算法不像动态规划算法需要考虑各种子问题的组合,它仅关注每一步的最优选择,因此通常更加高效。
思路:可以大饼干先喂胃口大的,也可以小饼干先喂胃口小的
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int count = 0;
int j = 0;
for(int i = 0;i
思路:有大钱先找大钱,20先给出10没有再用5
class Solution {
public boolean lemonadeChange(int[] bills) {
if(bills[0]>5){
return false;
}
int[] change = new int[2];
for(int i = 0;i0){
change[1]--;
change[0]--;
if(change[0]<0){
return false;
}
}else if(change[0]>=3){
change[0] -= 3;
}else{
return false;
}
}
}
return true;
}
}
思路:从左往右只要右边比左边大就加1,从右往左只要左边比右边大就加1,取最大
class Solution {
public int candy(int[] ratings) {
int len = ratings.length;
int[] minCandy = new int[len];
minCandy[0] = 1;
for(int i = 0;i ratings[i]){
minCandy[i+1] = minCandy[i] + 1;
} else{
minCandy[i+1] = 1;
}
}
for(int i = len -2;i>=0;i--){
if(ratings[i] > ratings[i+1]){
minCandy[i] = Math.max(minCandy[i+1] + 1,minCandy[i]);
}
}
int res = 0;
for(int i =0;i