算法练习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 
相关推荐
老刘说AI几秒前
WorkFlow Agent案例:auto_document_agent(文件自动处理)
开发语言·数据库·人工智能·python·神经网络·自然语言处理
AI成长日志10 分钟前
【强化学习专栏】深度强化学习技术演进:DQN、PPO、SAC的架构设计与训练优化
人工智能·算法·架构
时寒的笔记12 分钟前
js逆向05_ob混淆花指令,平坦流,某麦网(突破ob混淆寻找拦截器)
开发语言·前端·javascript
郭逍遥14 分钟前
[Godot] JPS跳点寻路和RVO避障
算法·godot·启发式算法
云烟成雨TD15 分钟前
Spring AI 1.x 系列【15】AI Agent 基石:Tool Calling 标准与 Spring AI 集成
java·人工智能·spring
咸鱼2.016 分钟前
【java入门到放弃】杂记
java·开发语言
rgb2gray18 分钟前
论文详解:基于POI数据的城市功能区动态演化分析——以北京为例
人工智能·算法·机器学习·回归·gwr
m0_7349980119 分钟前
Day 26
数据结构·c++·算法
信奥卷王31 分钟前
2026年03月GESPC++二级真题解析(含视频)
算法
从零开始学习人工智能35 分钟前
国产阿特拉斯无人机蜂群核心算法(一)
算法·无人机