算法练习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 
相关推荐
FQNmxDG4S1 小时前
Java多线程编程:Thread与Runnable的并发控制
java·开发语言
超级码力6661 小时前
【Latex文件架构】Latex文件架构模板
算法·数学建模·信息可视化
穿条秋裤到处跑2 小时前
每日一道leetcode(2026.04.29):二维网格图中探测环
算法·leetcode·职场和发展
前端老石人2 小时前
HTML 字符引用完全指南
开发语言·前端·html
matlab_xiaowang2 小时前
Redux 入门:JavaScript 可预测状态管理库
开发语言·javascript·其他·ecmascript
Merlos_wind2 小时前
HashMap详解
算法·哈希算法·散列表
虹科网络安全2 小时前
艾体宝干货|数据复制详解:类型、原理与适用场景
java·开发语言·数据库
axng pmje3 小时前
Java语法进阶
java·开发语言·jvm
汉克老师3 小时前
GESP2025年3月认证C++五级( 第三部分编程题(1、平均分配))
c++·算法·贪心算法·排序·gesp5级·gesp五级
rKWP8gKv73 小时前
Java微服务性能监控:Prometheus与Grafana集成方案
java·微服务·prometheus