• 算法通关村第17关【青铜】| 贪心


    贪心算法(Greedy Algorithm)是一种常见的算法设计策略,通常用于解决一类优化问题。其核心思想是:在每一步选择中都采取当前状态下的最优决策,从而希望最终能够达到全局最优解。贪心算法不像动态规划算法需要考虑各种子问题的组合,它仅关注每一步的最优选择,因此通常更加高效。

    1. 分发饼干

    思路:可以大饼干先喂胃口大的,也可以小饼干先喂胃口小的

    1. class Solution {
    2. public int findContentChildren(int[] g, int[] s) {
    3. Arrays.sort(g);
    4. Arrays.sort(s);
    5. int count = 0;
    6. int j = 0;
    7. for(int i = 0;i
    8. while(j
    9. j++;
    10. }
    11. if(j
    12. count++;
    13. }
    14. j++;
    15. }
    16. return count;
    17. }
    18. }

    2. 柠檬水找零

    思路:有大钱先找大钱,20先给出10没有再用5

    1. class Solution {
    2. public boolean lemonadeChange(int[] bills) {
    3. if(bills[0]>5){
    4. return false;
    5. }
    6. int[] change = new int[2];
    7. for(int i = 0;i
    8. if(bills[i] == 5){
    9. change[0]++;
    10. continue;
    11. }
    12. if(bills[i] == 10){
    13. change[0]--;
    14. change[1]++;
    15. if(change[0]<0){
    16. return false;
    17. }
    18. }else{
    19. if(change[1]>0){
    20. change[1]--;
    21. change[0]--;
    22. if(change[0]<0){
    23. return false;
    24. }
    25. }else if(change[0]>=3){
    26. change[0] -= 3;
    27. }else{
    28. return false;
    29. }
    30. }
    31. }
    32. return true;
    33. }
    34. }

    3. 分发糖果

    思路:从左往右只要右边比左边大就加1,从右往左只要左边比右边大就加1,取最大

    1. class Solution {
    2. public int candy(int[] ratings) {
    3. int len = ratings.length;
    4. int[] minCandy = new int[len];
    5. minCandy[0] = 1;
    6. for(int i = 0;i1;i++){
    7. if(ratings[i + 1] > ratings[i]){
    8. minCandy[i+1] = minCandy[i] + 1;
    9. } else{
    10. minCandy[i+1] = 1;
    11. }
    12. }
    13. for(int i = len -2;i>=0;i--){
    14. if(ratings[i] > ratings[i+1]){
    15. minCandy[i] = Math.max(minCandy[i+1] + 1,minCandy[i]);
    16. }
    17. }
    18. int res = 0;
    19. for(int i =0;i
    20. res += minCandy[i];
    21. }
    22. return res;
    23. }
    24. }

  • 相关阅读:
    maven 更新jar包 仓库下载不下来
    【图形学】 06 四元数(一)
    【Java题】实现继承和多态的例子
    使用Docker安装Redis
    Spring MVC的核心类和注解——@RequestMapping注解(一)@RequestMapping注解的使用
    App Deploy as Code! SAE & Terraform 实现 IaC 式部署应用
    LM06丨仅用成交量构造抄底摸顶策略的奥秘
    threejs(7)-精通粒子特效
    python venv在linux上激活环境无效,没反应
    Typescript
  • 原文地址:https://blog.csdn.net/Candy___i/article/details/133635261