121. Best Time to Buy and Sell Stock

代码如下:

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) == 0:
            return 0
        if len(prices) == 1:
            return 0
        minp= prices[0];
        profit = 0;
        for i in range(len(prices)):
            if prices[i] < minp:
                minp = prices[i]
            else:
                profit = max(profit, prices[i] - minp)
        return profit
        

动态规划的思想,每一步都是当前的最优值。代码如下:

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) == 0 or len(prices) == 1:
            return 0
        best_price = prices[0]
        max_profit = 0
        for p in prices:
            best_price = min(best_price, p)
            max_profit = max(max_profit, p - best_price)
        return max_profit
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容