LeetCode——Best Time to Buy and Sell Stock

24 篇文章 0 订阅
17 篇文章 0 订阅
LeetCode——Best Time to Buy and Sell Stock

# 121

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:

Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

这一题的目的是求数组中,找出两个相差最大的元素,必须是后一个元素减去前一个元素。这一题明显是动态规划。当然可以用暴力破解,时间复杂度为 O(n2) 。 暴力破解法就不写了。
有一种简单的思想就是,就是使用一次遍历,记录遍历过程中的最小元素,并将当前值与当前遍历的最小元素的差记录为最大利润。遍历结束后,即能得到最大利润。

  • C++
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0, buy = INT_MAX;
        for (int price : prices) {
            buy = min(buy, price);
            res = max(res, price - buy);
        }
        return res;
    }
};

动态规划的方法,其实思想是和前面做过的一题Maximum Subarray 很相似。就是要用两个变量分别维护局部最优全局最优

  • C++
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size() == 0)
            return 0;
        int local = 0;
        int global = 0;
        for(int i = 0;i < prices.size() - 1;i++) {
            local = max(local + prices[i + 1] - prices[i],0);
            global = max(local,global);
        }
        return global;
    }
};

这里的动态规划思想和Maximum Subarray的思想是一样的,设置两个变量,维护局部最优和全局最优。

  • Python
class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) <= 1: return 0
        low = prices[0]
        maxprofit = 0
        for i in range(len(prices)):
            if prices[i] < low: low = prices[i]
            maxprofit = max(maxprofit, prices[i] - low)
        return maxprofit
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值