Leetcode-Easy 121. Best Time to Buy and Sell Stock

简介: Leetcode-Easy 121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock


  • 描述:

13.png

  • 思路:

[1,2,3,4] ==> returns 3 (buy at 1 and sell at 4)

[4,3,2,1] ==> returns 0 (don't buy)

[4,10,25,2,10] ==> returns 21 (buy at 4 and sell at 25)

遍历每天的价格,与当前最低价格相比较min_price;然后当前价格减去最低价格,算出当前利润profit;当前利润与最大利润相比较,得出结果。


  • 代码

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        max_profit, min_price = 0, float('inf')
        for price in prices:
            min_price=min(min_price,price)
            profit=price-min_price
            max_profit=max(max_profit,profit)
        return max_profit


相关文章
|
算法
LeetCode 309. Best Time to B & S Stock with CD
给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。 设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票)
53 0
LeetCode 309. Best Time to B & S Stock with CD
|
算法
LeetCode 188. Best Time to Buy and Sell Stock IV
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。
60 0
LeetCode 188. Best Time to Buy and Sell Stock IV
|
算法
LeetCode 123. Best Time to Buy and Sell Stock III
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。 注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
75 0
LeetCode 123. Best Time to Buy and Sell Stock III
|
算法
LeetCode 121. Best Time to Buy and Sell Stock
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 如果您最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
50 0
LeetCode 121. Best Time to Buy and Sell Stock
|
算法
LeetCode 121 Best Time to Buy and Sell Stock(股票买入卖出的最佳时间)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50814399 翻译 话说你有一个数组,其中第i个元素表示在第i天的股票价格。
838 0
|
算法
LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50829772 翻译 话说你有一个数组,其中第i个元素表示第i天的股票价格。
844 0
|
2月前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
2月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
2月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3
|
2月前
|
容器
《LeetCode》——LeetCode刷题日记1
《LeetCode》——LeetCode刷题日记1

热门文章

最新文章