马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Seawolf 于 2020-9-10 22:33 编辑
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 k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
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.
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
#hold, sold
if k <= 0 or prices == None or len(prices) == 0:
return 0
#the maximum trahsanction time is less than k
if 2 * k > len(prices):
res = 0
for i in range(1, len(prices)):
res += max(0, prices[i] - prices[i - 1])
return res
#regular case
dp = [[-math.inf, 0] for _ in range(k)]
for price in prices:
temp = dp
for i in range(k):
if i == 0:
dp[i][0] = max(temp[i][0], 0 - price)
dp[i][1] = max(temp[i][1], temp[i][0] + price)
else:
dp[i][0] = max(temp[i][0], temp[i - 1][1] - price)
dp[i][1] = max(temp[i][1], temp[i][0] + price)
return dp[-1][-1]
|