首页 > 其他分享 >day27-greedy-part01-7.29

day27-greedy-part01-7.29

时间:2024-07-29 15:53:44浏览次数:10  
标签:count snack 7.29 part01 day27 int result 最优 贪心

tasks for today:

1.理论基础

2.455.分发饼干

3.376.摆动序列

4.53.最大子序和

------------------------------------------------------------------

1.理论基础

(1)贪心的本质是选择每一阶段的局部最优,从而达到全局最优

经常与贪心算法放在一起进行比较的就是动态规划,以下是一个例子:

例如,有一堆钞票,你可以拿走十张,如果想达到最大的金额,你要怎么拿?

指定每次拿最大的,最终结果就是拿走最大数额的钱。

每次拿最大的就是局部最优,最后拿走最大数额的钱就是推出全局最优。

再举一个例子如果是 有一堆盒子,你有一个背包体积为n,如何把背包尽可能装满,如果还每次选最大的盒子,就不行了。这时候就需要动态规划。

(2)贪心算法并没有固定的套路, 唯一的难点就是如何通过局部最优,推出整体最优。

那么如何能看出局部最优是否能推出整体最优呢?有没有什么固定策略或者套路呢?也没有!

靠自己手动模拟,如果模拟可行,就可以试一试贪心策略,如果不可行,可能需要动态规划。

(3)如何验证可不可以用贪心算法呢

最好用的策略就是举反例,如果想不到反例,那么就可试一试贪心算法

手动模拟一下感觉可以局部最优推出整体最优,而且想不到反例,那么就试一试贪心

(4)贪心算法一般分为如下四步:

  • 将问题分解为若干个子问题
  • 找出适合的贪心策略
  • 求解每一个子问题的最优解
  • 将局部最优解堆叠成全局最优解

2.455.分发饼干

In this practice, teh greedy idea is to use the smallest snack to go through the kids' appetite. Before the operation, both the snack and the kids should be sorted, and the additinal index lists should be used to control the left kids.

class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        g.sort()
        s.sort()
        result = 0
        index_kid = list(range(len(g)))

        for snack in s:
            # print('snack', snack)
            for j in index_kid:
                # print('kid', g[j])
                if snack >= g[j]:
                    result += 1
                    index_kid.pop(index_kid.index(j))
                    break
        
        return result

There is another valid mindset is, use the largest snack to satisfy the biggest appetite.

3.376.摆动序列

In this practice, the key idea is to count the number of local maxmium.

One point need to be paied attention to is the special circumstance.

Another is when to update "prediff", the answer is only if the peek shows up, otherwise, the prediff will not be updated.

Only the curdiff is updated iteratively.

class Solution:
    def wiggleMaxLength(self, nums: List[int]) -> int:
        if len(nums) <= 1: return len(nums)
        if len(nums) == 2 and nums[0] != nums[1]: return 2
        elif len(nums) == 2 and nums[0] == nums[1]: return 1

        result = 1
        curdiff = 0
        prediff = 0
        for i in range(len(nums) - 1):
            curdiff = nums[i+1] - nums[i]
            if (prediff>= 0 and curdiff<0) or (prediff<=0 and curdiff>0):
                result += 1
                prediff = curdiff

        return result

4.53.最大子序和

Apart from raw search, the greedy method is reflected on the update of count. For the record, the update of results only happens when count is greater than current result. This may be a little tricky to understand especially when all the elemnts are negetive, but if you do a few steps simulation, the result is still correct.

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        result = float('-inf')
        count = 0
        for i in range(len(nums)):
            count += nums[i]
            if count > result:
                result = count
            if count <= 0:
                count = 0
        
        return result

标签:count,snack,7.29,part01,day27,int,result,最优,贪心
From: https://blog.csdn.net/bbrruunnoo/article/details/140767376

相关文章

  • 【新方法】1分钟搞定2024暑期教师研修!(7.29更新)
    写在前面代码失效,现在采用修复后的油猴脚本,跟代码区别就是隔几秒再点下一个视频即可,学时可以记录上。仅限于中小学,职教和高教不可以。不会操作可以绿泡泡daikan856.脚本https://greasyfork.org/zh-CN/scripts/486386-2024年智慧中小学暑假教师研修-秒过-每个视频只点1遍-不懂先......
  • 7.29第三周周一学习总结
    洛谷题单https://www.luogu.com.cn/training/9349字符串读入getline(cin,a);//读入一行包括空格for(inti=0;i<a.size();i++){ if(a[i]!=''&&a[i]!='\n') ans++;}打表和ascl运用点击查看代码#include<stdio.h>intmain(void){chara[14],mod[1......
  • 代码随想录算法训练营第22天-leetcode-回溯算法part01:
    #回溯算法理论基础能解决的问题:组合问题:N个数里面按一定规则找出k个数的集合切割问题:一个字符串按一定规则有几种切割方式子集问题:一个N个数的集合里有多少符合条件的子集排列问题:N个数按一定规则全排列,有几种排列方式棋盘问题:N皇后,解数独等等第77题.组合力扣题目链接(op......
  • DAY10 栈与队列part01
     理论基础文章讲解:https://programmercarl.com/%E6%A0%88%E4%B8%8E%E9%98%9F%E5%88%97%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80.html232.用栈实现队列 注意为什么要用两个栈题目链接/文章讲解/视频讲解:https://programmercarl.com/0232.%E7%94%A8%E6%A0%88%E5%AE%9E%E7%8E%......
  • 代码随想录算法训练营第二十二天|回溯算法part01
    第77题.组合在单个集合1-n中,寻找所有个数为k的组合。和所有递归一样,都有三部曲。确定参数与返回值确定终止条件单层逻辑首先,回溯算法的返回值一般是void,参数依照题目要求而增加,在这一题中,参数有n,k还有startIndex。终止条件是path的size等于k,将path存放在result中。......
  • Day 22 回溯算法 part01
    77.组合我的这个解法还算挺简单易懂的,还是看注释classSolution{List<List<Integer>>ans=newArrayList();//存储最终结果集合List<Integer>tmp=newArrayList();//记录单次的pathpublicList<List<Integer>>combine(intn,intk){backTr......
  • 「代码随想录算法训练营」第十九天 | 回溯算法 part01
    回溯算法模板voidbacktracking(参数){if(终止条件){存放结果;return;}for(选择:本层集合中元素(树中节点孩子的数量就是集合的大小)){处理节点;backtracking(路径,选择列表);//递归回溯,撤销处理结果}}......
  • 第四十八天 第十章 单调栈part01 739. 每日温度 496.下一个更大元素 I 503.下一个更大
     739.每日温度 使用单调栈:注意栈中的递增递减顺序。classSolution{public:vector<int>dailyTemperatures(vector<int>&temperatures){vector<int>res(temperatures.size(),0);stack<int>sta;sta.push(0);for(int......
  • 代码随想录day27 递增子序列 | 全排列 | 全排列 II
    递增子序列递增子序列解题思路用set来去重,之后每次一个节点存入时与前一个节点进行大小比较,如果小就不存了,跳过剩余的回溯过程知识点回溯,去重心得在考虑去重的时候忘记了使用C++的数据结构set,得记下这个方法全排列全排列解题思路在回溯迭代的时候传入了一个统计数组元......
  • Day 13 二叉树part01
    Day13二叉树part01二叉树的递归遍历这个用递归就好,现在写起来基本没问题二叉树的迭代遍历这个是重点,今天写的时候居然一次写出来了,多刷还是有用的。前中后三种遍历方式,其迭代版本的难度排序前<中<后。所以写的时候也是按这个顺序去做的。144.二叉树的前序遍历使用一......