Say you has 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. Transactions at the most K .
Note:
Engage in multiple transactions on the same time (ie, you must sell the stock before you buy again).
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Based on Dynamic Planning
Maintain II vectors:gpro:to Day I the maximum profit
lpro:to Day I, the maximum profit with jth sell by day I
The complexity of this problem is O (k*n)
Code is as follow:
Class solution: # @return An integer as the maximum profit def helper (self, prices): Pro = 0 for i in rang E (LEN (prices)-1): Pro = Max (pro, Pro + prices[i+1]-prices[i]) return pro def maxprofit (self, k, prices):
m = Len (prices) if M = = 0: return 0 if K >= m:### if K >=m this problem become best time to sell ii< C11/>return Self.helper (prices) Lpro = [0] * (k + 1) Gpro = [0] * (k + 1) for I in range (len (prices)-1): C15/>dif = prices[i + 1]-prices[i] j = k while J >= 1: lpro[j] = max (Gpro[j-1]+max (0,DIF), Lpro[j] + D IF) gpro[j] = max (Gpro[j], lpro[j]) j-=1 return gpro[k]
188. Best time to Buy and Sell Stock IV leetcode Python