算法练习Day26 (Leetcode/Python-贪心算法)

122. Best Time to Buy and Sell Stock II

You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.

Find and return the maximum profit you can achieve.

Example 1:

复制代码
Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.

思路:可以无数次买入卖出一支股票,求最大收益。那么只要每两天之间的股票是见涨的,就应该买入。用一个for循环遍历就可以了。

每两天是一个交易单元,局部最优->全局最优,即贪心算法。

python 复制代码
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        result = 0
        if len(prices) <= 1:
            return result
        for i in range(1, len(prices)):
            result += max(0, prices[i]-prices[i-1])
        return result

55. Jump Game

You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.

Return trueif you can reach the last index, or falseotherwise.

Example 1:

复制代码
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

思路:每次都可以跳<=当前格子数值的步数,判断最后是否可以到达终点。因为接下来小于等于当前格子数值的格子都是理论上可以到达的。那么就看最大的coverage是不是包含终点就可以了,不用纠结到底选择了哪一个格子。

python 复制代码
class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        cover = 0 
        if len(nums) == 1: return True
        for i in range(len(nums)):
            if i <= cover:
                cover = max(i + nums[i], cover)
                if cover >= len(nums) - 1: return True
        return False 
相关推荐
Max_uuc1 分钟前
【C++ 硬核】打破嵌入式 STL 禁忌:利用 std::pmr 在“栈”上运行 std::vector
开发语言·jvm·c++
吃杠碰小鸡2 分钟前
高中数学-数列-导数证明
前端·数学·算法
故事不长丨2 分钟前
C#线程同步:lock、Monitor、Mutex原理+用法+实战全解析
开发语言·算法·c#
long3162 分钟前
Aho-Corasick 模式搜索算法
java·数据结构·spring boot·后端·算法·排序算法
近津薪荼3 分钟前
dfs专题4——二叉树的深搜(验证二叉搜索树)
c++·学习·算法·深度优先
牵牛老人5 分钟前
【Qt 开发后台服务避坑指南:从库存管理系统开发出现的问题来看后台开发常见问题与解决方案】
开发语言·qt·系统架构
熊文豪12 分钟前
探索CANN ops-nn:高性能哈希算子技术解读
算法·哈希算法·cann
froginwe1113 分钟前
Python3与MySQL的连接:使用mysql-connector
开发语言
熊猫_豆豆29 分钟前
YOLOP车道检测
人工智能·python·算法
rannn_11129 分钟前
【苍穹外卖|Day4】套餐页面开发(新增套餐、分页查询、删除套餐、修改套餐、起售停售)
java·spring boot·后端·学习