• 打败算法 —— 买卖股票的最佳时机


    本文参考

    出自LeetCode上的题库 —— 买卖股票的最佳时机

    https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/

    买卖股票问题

    给定一个数组 prices,它的第 i 个元素prices[i] 表示一支给定股票第 i 天的价格
    选择某一天买入这只股票,并选择在未来的某一个不同的日子卖出该股票
    返回你可以从这笔交易中获取的最大利润;如果你不能获取任何利润,返回 0

    示例1:
    输入: [7, 1, 5, 3, 6, 4]
    输出: 5

    示例2:
    输入:[7, 6, 4, 3, 1]
    输出:0

    解题思路

    利用滑动窗口的思想,基本解题步骤为:

    1、初始化左右指针的下标索引$left=right=0$,索引闭区间$[left,right]$为一个窗口
    2、不断地增加$right$指针扩大窗口$[left,right]$,判断$profit < (prices[right]-prices[left])$,直到$prices[left]>prices[right]$
    3、此时,停止移动$right$指针,移动$left$指针到$right$指针的位置
    4、重复第2和第3步,直到$right$指针到达列表的尽头

    滑动窗口解法

    class Solution:
      def max_profit(self, prices: List[int]) -> int:
        left = right = 0
        ans = -1
        while right < len(prices):
          while right < len(prices) and prices[left] <= prices[right]:
            if ans < prices[right] - prices[left]:
              ans = prices[right] - prices[left]
            right += 1
          left = right
    return ans

  • 相关阅读:
    FZU2150 Fire Game
    POJ3414 Pots
    POJ3087 Shuffle'm Up
    POJ3126 Prime Path
    POJ1426 Find The Multiple
    POJ3279 Fliptile
    甘特图实用技巧——项目进度一目了然!
    连设计图都不会画,你还想做“系统架构师”?
    java中list和map的底层实现原理
    redis四种部署方式
  • 原文地址:https://www.cnblogs.com/kuluo/p/15975492.html
Copyright © 2020-2023  润新知