动态规划---最好的一天买卖股票

1、题目

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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 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
Explanation: In this case, no transaction is done, i.e. max profit = 0.

2、解答:找到第i天之前买入最低的价格,与第i天的价格相减,若大于最大利润,则保留,否则放弃。

3、代码

python代码

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        n = len(prices)
        if n < 1:
            return 0
        
        max_profit = 0
        low_price = prices[0]
        for i in range(1,n):
            low_price = min(low_price,prices[i])
            max_profit = max(max_profit,prices[i]-low_price)
        return max_profit

    C++代码

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        if(n < 1)
            return 0;
       int max_profit = 0;
       int low_price = prices[0];
       for(int i=1;i<n;i++){
           low_price = min(low_price,prices[i]);
           max_profit = max(max_profit,prices[i] - low_price);
       }
     return max_profit;  
    }
};

猜你喜欢

转载自blog.csdn.net/qq_31307013/article/details/80575876