121. Best Time to Buy and Sell Stock - 交易1次
题目描述
假设有一个数组,第i个元素 - 股票在第i天的价格。
要求最多交易一次(即,买一次和卖一次),设计算法得到最大收益。
注意:不能在买股票前卖股票。
例子
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.
思想
(贪心)
法1 - 贪心,记录截止当前日期的最小buy。从前向后遍历,保留最小值;
法2 - 贪心,记录当前及其之后日期的最大sell。从后向前遍历,保留最大值;
(DP)法1的两种方法均可DP求解,下面以1.1为例。
法3 - buys[i]表示截止第i天的最小buy,则buys[i] = min(buys[i-1], prices[i])
解法1
贪心。从前向后遍历,记录截止当前日期的最小buy。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
res = 0
buy = prices[0] # Record the min-buy up to this time
for price in prices[1:]:
if price > buy:
res = max(res, price - buy)
else:
buy = price
return res
解法2
贪心。从后向前遍历,记录当前及其之后日期的最大sell。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
res = 0
sell = prices[-1] # Record the max-sell after this time
for price in prices[:-1][::-1]:
if price > sell:
sell = price
else:
res = max(res, sell - price)
return res
解法3
DP
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
buys = [0] * len(prices) # Record the min-buy up to this time
buys[0] = prices[0]
for i in range(1, len(prices)):
buys[i] = min(buys[i-1], prices[i])
res = 0
for i in range(len(prices)):
res = max(res, prices[i] - buys[i])
return res
122. Best Time to Buy and Sell Stock II - 交易多次
题目描述
假设有一个数组,第i个元素 - 股票在第i天的价格。
可以交易多次(即,买卖次),设计算法得到最大收益。
注意:不能在买股票前卖股票。
例子
Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 =
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
思想
(贪心)
法1 - 只需关注递增的差值,求和。
比如12314,1买进3卖出 + 1买进4卖出
⇔
\Leftrightarrow
⇔ 1买进2卖出 + 2买进3卖出 + 1买进4卖出
(DP)
法2 - 第i天之前只有两种状态:最后一个操作是买buy和最后一个操作是卖sell。
buy[i] = max(buy[i-1],sell[i-1] - prices[i]);
sell[i] = max(sell[i-1],buy[i-1] + prices[i]);
解法1
贪心。只需关注递增的差值,求和。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
res = 0
for i in range(1, len(prices)):
res += max(0, prices[i] - prices[i-1])
return res
解法1.1
小优化
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
res = 0
buy = prices[0]
for price in prices[1:]:
if price > buy:
res += price - buy
buy = price
return res
解法2
DP,第i天之前两种状态:最后一个操作是买buy和最后一个操作是卖sell。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
buy, sell = -prices[0], 0
for price in prices:
buy = max(buy, sell - price)
sell = max(sell, buy + price)
return sell
123. Best Time to Buy and Sell Stock III - 最多交易2次
题目描述
假设有一个数组,第i个元素 - 股票在第i天的价格。
要求最多交易2次,设计算法得到最大收益。
注意:不能在买股票前卖股票。
例子
Example 1:
Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
思想
(贪心)
法1 - 两轮遍历,一个从前往后,一个从后往前。计算第i天之前进行1次交易的最大收益,和第i天之后进行1次交易的最大收益。
首先,从前往后遍历,保留最小值buy → 记录截止第i天(包含第i天)的maxProfit;
然后,从后往前遍历,保留最大值sell → 记录第i天之后(不包含第i天)的maxProfit。
注意 - 可能只交易1次,所以保留遍历一趟后profit的值。
(DP)
法2 - 第i天有4种状态:第一笔交易买入状态最大收益buy1和第一笔交易卖出状态最大收益sell1,第二笔交易买入状态最大收益buy2和第二笔交易卖出状态最大收益sell2。
则有下列状态方程:
sell2[i] = max(sell2[i-1], buy2[i-1] + prices[i])
buy2[i] = max(buy2[i-1], sell1[i-1] - prices[i])
sell1[i] = max(sell1[i-1], buy1[i-1] + prices[i])
buy1[i] = max(buy1[i-1], - prices[i])
解法1
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
# Record min-buy
profits = [0]
buy, profit = prices[0], 0
for price in prices[1:]:
buy = min(buy, price)
profit = max(profit, price-buy)
profits.append(profit)
# Record max-sell - Note remember the value of profit
sell = prices[-1]
temp = 0
for i in range(len(prices)-1, 0, -1):
sell = max(sell, prices[i])
temp = max(temp, sell - prices[i])
profit = max(profit, temp + profits[i-1])
return profit
解法2
DP
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
buy1 = buy2 = float('-inf')
sell1 = sell2 = 0
for price in prices:
buy1 = max(buy1, -price)
sell1 = max(sell1, buy1 + price)
buy2 = max(buy2, sell1 - price)
sell2 = max(sell2, buy2 + price)
return sell2
188. Best Time to Buy and Sell Stock IV - 最多交易k次
题目描述
假设有一个数组,第i个元素 - 股票在第i天的价格。
要求最多交易k次,设计算法得到最大收益。
注意:不能在买股票前卖股票。
例子
Example 1:
Input: [2,4,1], k = 2
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
Example 2:
Input: [3,2,6,5,0,3], k = 2
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4.
Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
思想
(DP-法1)
dp[i][j]表示第j天完成i次交易的最大收益。(买入+卖出一个来回才算一次交易。)
注:外层循环是交易次数k,内层循环是天数n,k < n/2,这样效率比较高.
dp[i][j]包含下面两种情况:
① 第j天不交易 dp[i][j-1]
② 第j天交易,即第j天卖出。假设第m天买入,则为prices[j] - prices[m] + dp[i-1][m-1],m=1,2…j-1 → 计算max(-prices[m] + dp[i-1][m-1]) → 遍历的同时,maxTemp = max(maxTemp, -prices[j] + dp[i-1][j-1])
状态方程为:dp[i][j] = max(dp[i][j-1],prices[j] + maxTemp)
(DP-法2)
类似123. Best Time to Buy and Sell Stock III的解法2,有k种状态。
(优化)
当k>n/2时,相当于多次交易(无数次交易),解法是122. Best Time to Buy and Sell Stock II,只需关注递增的差值,求和。
解法1
复杂度:时间O(n),空间O(nk) - 可优化成O(k)。
class Solution(object):
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
n = len(prices)
if k > (n>>1):
return self.helper(prices)
dp = [[0] * n for _ in range(k+1)] # dp[i][j]表示第j天完成i次交易的最大收益
for i in range(1, k+1):
maxTemp = -prices[0]
for j in range(1, n):
maxTemp = max(maxTemp, -prices[j] + dp[i-1][j-1])
dp[i][j] = max(dp[i][j-1], prices[j] + maxTemp)
return dp[-1][-1]
def helper(self, prices):
res = 0
buy = prices[0]
for price in prices[1:]:
if price > buy:
res += price - buy
buy = price
return res
解法2
复杂度:时间O(n),空间O(k)。
class Solution(object):
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
n = len(prices)
if k > (n>>1):
return self.helper(prices)
buy = [float('-inf')] * (k+1)
sell = [0] * (k+1)
for price in prices:
for j in range(1, k+1):
buy[j] = max(buy[j], sell[j-1] - price)
sell[j] = max(sell[j], buy[j] + price)
return sell[-1]
def helper(self, prices):
res = 0
buy = prices[0]
for price in prices[1:]:
if price > buy:
res += price - buy
buy = price
return res
309. Best Time to Buy and Sell Stock with Cooldown - 冷却1天
题目描述
假设有一个数组,第i个元素 - 股票在第i天的价格。
要求可以交易多次,但卖股票后冷却1天,设计算法得到最大收益。
冷却1天:在出售股票后,无法在第二天购买股票。
例子
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
思想
(DP)
第i天之前只有两种状态:最后一个操作是买buy和最后一个操作是卖sell。
buy[i] = max(buy[i-1],sell[i-2] - prices[i]);
sell[i] = max(sell[i-1],buy[i-1] + prices[i]);
解法
复杂度:时间O(n),空间O(n)。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
n = len(prices)
buy = [float('-inf')] * (n+2)
sell = [0] * (n+2)
for i in range(2, n+2):
buy[i] = max(buy[i-1], sell[i-2] - prices[i-2])
sell[i] = max(sell[i-1], buy[i-1] + prices[i-2])
return sell[-1]
解法 优化
复杂度:时间O(n),空间O(1)。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
buy = float('-inf')
sell = lastSell = 0
for price in prices:
buy = max(buy, lastSell - price)
lastSell = sell
sell = max(sell, buy + price)
return sell
714. Best Time to Buy and Sell Stock with Transaction Fee - 有交易费用
题目描述
假设有一个数组,第i个元素 - 股票在第i天的价格。
要求可以交易多次,但有交易费用,设计算法得到最大收益。
例子
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
Buying at prices[0] = 1
Selling at prices[3] = 8
Buying at prices[4] = 4
Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
思想
(DP)
第i天之前只有两种状态:最后一个操作是买buy和最后一个操作是卖sell。
buy[i] = max(buy[i-1],sell[i-1] - prices[i]);
sell[i] = max(sell[i-1],buy[i-1] + prices[i] - fee);
解法
class Solution(object):
def maxProfit(self, prices, fee):
"""
:type prices: List[int]
:type fee: int
:rtype: int
"""
if not prices:
return 0
buy = -prices[0]
sell = 0
for price in prices[1:]:
buy = max(buy, sell - price)
sell = max(sell, buy + price - fee)
return sell
总结
要求 | Solution |
---|---|
交易1次 | 从前向后遍历,保留当前日期的最小buy |
最多交易2次 | 两轮遍历,计算第i天之前进行1次交易的最大收益,和第i天之后进行1次交易的最大收益 |
最多交易k次 | ① dp[i][j]表示第j天完成i次交易的最大收益;② 外层循环天数,内层循环2k种状态:buy1…buyk,sell1…sellk。优化-k>n/2时,相当于多次交易 |
交易多次 | 只需关注递增的差值,求和 |
冷却1天 | DP,第i天之前只有两种状态:最后一个操作是买buy和最后一个操作是卖sell |
有交易费用 | DP,第i天之前只有两种状态:最后一个操作是买buy和最后一个操作是卖sell |