LeetCode 121. 买卖股票的最佳时机

2022-08-17  本文已影响0人  草莓桃子酪酪
题目

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

例:
输入:[7,1,5,3,6,4]
输出:5
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。

方法:暴力解法

计算每天若要选择卖出的话的最大利润,通过两个循环实现

class Solution(object):
    def maxProfit(self, prices):
        result = 0
        for i in range(1, len(prices)):
            for j in range(i):
                if prices[i] - prices[j] > result:
                    result = prices[i] - prices[j]
        return result

超出时间限制

方法:贪心算法
class Solution(object):
    def maxProfit(self, prices):
        result = 0
        low = float('inf')
        for i in range(len(prices)):
            low = min(low, prices[i])
            result = max(result, prices[i] - low)
        return result
方法:动态规划
class Solution(object):
    def maxProfit(self, prices):
        dp = [[0] * 2 for row in range(len(prices))]
        dp[0][0], dp[0][1] = -prices[0], 0
        for i in range(1, len(prices)):
            dp[i][0] = max(dp[i-1][0], -prices[i])
            dp[i][1] = max(dp[i-1][1], prices[i] + dp[i-1][0])
        return dp[-1][1]
参考

代码相关:https://programmercarl.com/0121.%E4%B9%B0%E5%8D%96%E8%82%A1%E7%A5%A8%E7%9A%84%E6%9C%80%E4%BD%B3%E6%97%B6%E6%9C%BA.html

上一篇 下一篇

猜你喜欢

热点阅读