本文共 3064 字,大约阅读时间需要 10 分钟。
Say you have an array for which the i th 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个元素表示第i天的股票的价格,如果你最多只允许进行一次交易(买进和卖出股票视为一次交易)
请设计一个算法得到最大利润。假设在某天卖出,只需知道这天之前最小的买入价格,设一个变量low记录就成
class Solution: def maxProfit(self, prices): if not prices: return 0 low = prices[0] maxprofit = prices[1] - prices[0] for i in range(2, len(prices)): low = min(low, prices[i - 1]) maxprofit = max(maxprofit, prices[i] - low) return maxprofitif __name__ == '__main__': a = [2, 3, 1, 2, 6, 5] so = Solution() print(so.maxProfit(a))
Say you have an array for which the i th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).允许进行多次交易,即可以多次买入和卖出,但手中最多只能持有一支股票,在再次买入的时候必须将之前的股票卖出,求能获取的最大利润。
一旦后一天比前一天大,就卖出,代码实际上是变相的统计了所有递增序列的末项-首项
class Solution: def maxProfit(self, prices): if not prices: return 0 maxprofit = 0 for i in range(1, len(prices)): if prices[i] > prices[i - 1]: maxprofit += prices[i] - prices[i - 1] return maxprofitif __name__ == '__main__': a = [2, 3, 1, 2, 6, 5] so = Solution() print(so.maxProfit(a))
Say you have an array for which the i th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).允许进行二次交易,即可以二次买入和卖出,但手中最多只能持有一支股票,在再次买入的时候必须将之前的股票卖出,求能获取的最大利润。
和第一题很相似,但是要分为两段来看
class Solution(): def maxProfit(self, prices): if not prices: return 0 n = len(prices) # pre_profit[i]表示i天之前的最大利润 pre_max_profit = [0] * n # pro_profit[i]表示i天之后的最大利润 pro_max_profit = [0] * n max_profit = 0 low = prices[0] for i in range(1, n): low = min(prices[i], low) pre_max_profit[i] = max(pre_max_profit[i - 1], prices[i] - low) # 求i天之后的最大利润,从后面找到最大的利润,再减去当天的 high = prices[n - 1] for k in range(n - 2, -1, -1): high = max(high, prices[k]) pro_max_profit[k] = max(pro_max_profit[k + 1], high - prices[k]) print(pro_max_profit) for j in range(n): max_profit = max(max_profit, pre_max_profit[j] + pro_max_profit[j]) return max_profitif __name__ == '__main__': a = [2, 3, 1, 2, 6, 5] so = Solution() print(so.maxProfit(a))
转载地址:http://qejmb.baihongyu.com/