• 算法题:买卖股票的最佳时机 II (贪心算法解决股票问题)


    这道题是贪心算法的中级难度练习题,由于题目设定,整个价格都是透明的,这里并不涉及需要预测股票涨势的问题。解决思路不难,就是一旦股票价格开始下降了就买入,一旦上升了,就赶紧卖出。(完整题目附在了最后)

    代码如下:

    1. class Solution(object):
    2. def maxProfit(self, prices):
    3. has_stock = False
    4. profit = 0
    5. for i in range(len(prices) - 1):
    6. if not has_stock:
    7. if i < len(prices) - 1 and prices[i] < prices[i + 1]:
    8. profit = profit - prices[i]
    9. has_stock = True
    10. elif has_stock:
    11. if prices[i] > prices[i + 1]:
    12. profit = profit + prices[i]
    13. has_stock = False
    14. if has_stock:
    15. return profit + prices[-1]
    16. elif profit == 0:
    17. profit = prices[-1] - prices[0]
    18. if profit < 0:
    19. return 0
    20. return profit

    完整题目:

    122. 买卖股票的最佳时机 II

    给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。

    在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。

    返回 你能获得的 最大 利润 。

    示例 1:

    输入:prices = [7,1,5,3,6,4]
    输出:7
    解释:在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4 。
         随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6 - 3 = 3 。
         总利润为 4 + 3 = 7 。

    示例 2:

    输入:prices = [1,2,3,4,5]
    输出:4
    解释:在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4 。
         总利润为 4 。

    示例 3:

    输入:prices = [7,6,4,3,1]
    输出:0
    解释:在这种情况下, 交易无法获得正利润,所以不参与交易可以获得最大利润,最大利润为 0 。
    

    提示:

    • 1 <= prices.length <= 3 * 10^4
    • 0 <= prices[i] <= 10^4
  • 相关阅读:
    Java随笔-反射
    软件确认测试有什么作用?确认测试报告的价格是多少?
    FPGA模块——IIC协议(读写PCF8591)
    C++ - std::string字符串格式化方法总结
    第84步 时间序列建模实战:Xgboost回归建模
    利用百度竞价排名推广增加转化率-华媒舍
    安卓布局优化详解
    serveless 思想 Midway.js 框架使用教程(四)
    【web-解析目标】(1.2.1)解析应用程序:确定用户输入入口
    【Redis线程模型】概念、模型图、原理_Redis10
  • 原文地址:https://blog.csdn.net/m0_37738114/article/details/133637839