LeetCode——Best Time to Buy and Sell Stock

来源:互联网 发布:无人驾驶数据标注 编辑:程序博客网 时间:2024/06/05 15:19

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: 5max. 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: 0In 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
原创粉丝点击