Best Time to Buy and Sell Stock - LeetCode


Best Time to Buy and Sell Stock - LeetCode
タイトル:
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. 分析:
この問題は私も動的計画でやることを選んだが、実は直接下界を探す方法もあるが、この間は主に動的計画を練習した.
まず、i日目の最大利益がPであると仮定すると、i+1日目の場合、このi+1日目の最小価格が最大利益より大きい場合、利益を更新し、そうでない場合、この日はしないことを選択します.i=1の場合、私たちはしないか買わないかを選ぶしかありません.最大利益は0です.
コード:
class Solution:
    # @param prices, a list of integer
    # @return an integer
    def maxProfit(self, prices):
        if not prices or len(prices)<2:
            return 0
        minprice = prices[0]
        profit = 0
        for i in prices:
            if i < minprice:
                minprice = i
            profit = max(profit,i-minprice)
        return profit