Best Time to Buy and Sell Stock IV
Say you have an array for which the ith 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).
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
[Solution]
这题如果一开始不重视 k 的条件限制,很容易误以为是一道简单的贪心题。
大概会想,无非就是找出序列中 所有的上升区段,并用上升区段的最后一个数减第一个数(即此上升区段的跨度)作为其 value,最后再取 前 k 个最大的 values 求和得解。
典型的贪心思想,我一开始这样想写的代码如下:
1 class Solution: 2 # @return an integer as the maximum profit 3 def maxProfit(self, k, prices): 4 if prices == []: 5 return 0 6 down = prices[0] 7 up = prices[0] 8 ansList = [] 9 for i in range(1, len(prices)): 10 if prices[i-1] < prices[i]: 11 up = prices[i] 12 elif prices[i] < prices[i-1]: 13 ansList.append(up - down) 14 down = prices[i] 15 up = prices[i] 16 ansList.append(up - down) 17 ansList.sort(reverse=True) 18 if k < len(ansList): 19 ans = sum(ansList[:k]) 20 else: 21 ans = sum(ansList) 22 return ans 23 24
而且这贪心可以过:200 / 211 test cases passed.
但细想一下,正是因为有 k 的限制,其实 贪心 是不对的。
考虑这样一个样例:
【未完待续】
时间: 2024-11-20 13:35:59