Leetcode 188. Best Time to Buy and Sell Stock IV
本帖最后由 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: , 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: , 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:
#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 - prices)
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 = max(temp, 0 - price)
dp = max(temp, temp + price)
else:
dp = max(temp, temp - price)
dp = max(temp, temp + price)
return dp[-1][-1]
页:
[1]