[LeetCode] #188. Best Time to Buy and Sell Stock IV
題目 You are given an integer array prices where prices[i] is the price of a given stock on the i th day, and an integer k . Find the maximum profit you can achieve. You may complete at most k transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). 直覺解 構想: 先找出所有可以低買高賣的時機,再從這些時機裡面挑出 k 個。挑選方式:while 迴圈,每圈會減少一個時機,減少方式有兩種,合併兩個相鄰的時機,或移除一個時機。 python 3 實作(失敗): class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: profit = 0 if len(prices) < 2 or k == 0: return profit # find all best time to buy and sell stock start = 0 intervals = [] while start < len(prices): interval = self.find_buy_sell_interval(start, prices) if interval['buy'] is None or interval['sell'] is None: break interval['subtotal'] = prices[interval[