算法练习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 
相关推荐
Micro麦可乐1 分钟前
最新Spring Security实战教程(十五)快速集成 GitHub 与 Gitee 的社交登录
java·spring boot·spring·gitee·github·spring security·社交登陆
u0104058363 分钟前
企业微信会话存档API对接中的敏感信息审计日志架构(Java版)
java·架构·企业微信
机器视觉知识推荐、就业指导4 分钟前
用 Qt 做商业软件,会不会“被迫开源”?
开发语言·qt·开源
Voyager First5 分钟前
ApereoCas学习系列一——从github克隆cas-server源码并启动
java
像少年啦飞驰点、5 分钟前
Spring Boot 从入门到实践:快速构建一个 RESTful API 服务
java·spring boot·后端开发·快速入门·restful api·编程小白
编程彩机6 分钟前
互联网大厂Java面试:从Spring Cloud到Kafka的技术场景深度解析
java·spring cloud·微服务·kafka·技术面试
波波0077 分钟前
每日一题:.NET 中什么是 LOH(大对象堆)?为什么频繁使用大数组或大字符串可能导致性能问题?如何优化?
java·jvm·算法
独自破碎E7 分钟前
动态规划-正则表达式匹配
算法·正则表达式·动态规划
Gofarlic_OMS8 分钟前
Fluent许可证使用合规性报告自动化生成系统
java·大数据·运维·人工智能·算法·matlab·自动化
智码未来学堂8 分钟前
C语言经典编程练习题(1)
c语言·开发语言