Crack LeetCode 之 121. Best Time to Buy and Sell Stock

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

这道题跟https://blog.csdn.net/tassardge/article/details/83000873类似,还是用一维动态规划中的“局部最优和全局最优法”。
我们迭代处理每天的价格,并且维护三个变量min_price、local和global。
min_price:该变量是到第i天为止的最低价格。
local:表示在第i天卖出的最大收益。很明显,local = max(0, prices[i] - min_price)
global:表示到目前为止的最大收益。global = max(global, local);

以下是C++代码和python代码,时间复杂度为O(n),空间复杂度为O(1)。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if (prices.empty())
            return 0;

        int global = 0;
        int local = 0;
        int min_price = prices[0];
        for (int i = 1; i<prices.size(); ++i) {
            if (min_price > prices[i])
                min_price = prices[i];

            local = max(0, prices[i] - min_price);
            global = max(global, local);
        }

        return global;
    }
};
class Solution:
	def maxProfit(self, prices):
		if prices == None or len(prices) == 0:
			return 0
		
		local = 0
		result = 0
		min = prices[0]
		for item in prices:
			if item < min:
				min = item
			
			if item >= min:
				local = item - min
			else:
				local = 0

			result = max( local, result )

		return result

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值