比较简单的俩个题,第一题O(n)的复杂度,第二题也想用O(n)的复杂度解决,刚开始出错了,直接用DP,毕竟最爱,虽然是O(n2)的复杂度,运行时间排名yefeichan
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(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ max_profile=0 if len(prices)==0: return max_profile min_price=prices[0] max_price=prices[0] for i in range(1,len(prices)): if prices[i]>max_price: if max_profile<(prices[i]-min_price): max_profile=prices[i]-min_price max_price=prices[i] if prices[i]<min_price: min_price=prices[i] max_price=prices[i] return max_profile
Say you have an array for which the ith 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) with the following restrictions:
- You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
- After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
prices = [1, 2, 3, 0, 2] maxProfit = 3 transactions = [buy, sell, cooldown, buy, sell]
class Solution(object): def maxProfit(self, prices): max_profile=[0]*(len(prices)+2) if len(prices)<2: return 0 for i in range(len(prices)-1,-1,-1): maxp=max_profile[i+1] for j in range(i+1,len(prices)): if prices[j]>prices[i]: if prices[j]-prices[i]+max_profile[j+2]>maxp: maxp=prices[j]-prices[i]+max_profile[j+2] max_profile[i]=maxp return max_profile[0]
本文介绍两种关于股票交易最大利润的算法实现。第一种算法针对单一交易的最大利润问题,采用一次遍历的方法,在O(n)的时间复杂度内找到最佳买卖时机。第二种算法处理允许多次交易的情况,并考虑了冷却期限制,通过动态规划方法在O(n)时间内计算最大利润。
269

被折叠的 条评论
为什么被折叠?



