121. Best Time to Buy and Sell Stock(股票最大收益)

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.



class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        vector<vector<int>> dp = vector<vector<int>>(n,vector<int>(2,0));
        //dp[i][j]:下标为 i 这一天结束的时候,手上持股状态为 j 时(0/1),我们持有的现金数
        //买入股票手上的现金数减少,卖出股票手上的现金数增加
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        for(int i = 1;i < n;i++) {
            // 今天没有持有 = 【昨天没持有】 【昨天持有了,今天卖掉】
            dp[i][0]  = max(dp[i-1][0],prices[i]+dp[i-1][1]);
            // 今天持有 = 【昨天没持有,今天买入,只有1次买入机会】, 【昨天持有】
            dp[i][1] = max(-prices[i], dp[i-1][1]);
            
        }
        return dp[n-1][0];
    }
};

 






状态压缩:
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        vector<int>dp(2,0);
        //dp[i][j]:下标为 i 这一天结束的时候,手上持股状态为 j 时(0/1),我们持有的现金数
        //买入股票手上的现金数减少,卖出股票手上的现金数增加
        dp[0] = 0;
        dp[1] = -prices[0];
        for(int i = 1;i < n;i++) {
            // 今天没有持有 = 【昨天没持有】 【昨天持有了,今天卖掉】
            dp[0]  = max(dp[0],prices[i]+dp[1]);
            // 今天持有 = 【昨天没持有,今天买入,只有1次买入机会】, 【昨天持有】
            dp[1] = max(-prices[i], dp[1]);
            
        }
        return dp[0];
    }
};

 








 暴力超时:

 1 class Solution:
 2     def maxProfit(self, prices):
 3         """
 4         :type prices: List[int]
 5         :rtype: int
 6         """
 7         n = len(prices)
 8         if n==0:
 9             return 0
10         max_diff = 0
11         for i in range(n):
12             for j in range(i,n):
13                 diff = prices[j]-prices[i]
14                 if diff>max_diff:
15                     max_diff = diff
16                     
17         return max_diff
18 
19         

 

 

只需要找出最大的差值即可,即 max(prices[j] – prices[i]) ,i < j。一次遍历即可,在遍历的时间用遍历low记录 prices[o….i] 中的最小值,就是当前为止的最低售价,时间复杂度为 O(n)。

class Solution:
    def maxProfit(self, a):
        """
        :type prices: List[int]
        :rtype: int
        """
        n = len(a)
        if n==0:
            return 0
        mins = a[0]
        max_diff = 0
        for i in range(1,n):
            #买入价也可以看成是卖出价
            
            #找到到截止到第i天的最低买入价
            if(a[i]<mins):
                mins = a[i]
            # 更新最大收益
            elif max_diff < a[i] - mins:
                max_diff = a[i] - mins
        return max_diff

        

 

 

posted @ 2018-04-08 10:48  乐乐章  阅读(187)  评论(0编辑  收藏  举报