best time to Buy and Sell Stock IV
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.
[Solution]
This problem if at first do not pay attention to the conditions of K, it is easy to mistakenly think it is a simple greedy problem.
Presumably, it is simply to find out all the ascending sections of the sequence, and use the last number of the ascending section minus the first number (that is, the span of the ascending section) as its value, and finally the first k of the largest values to sum the solution.
The typical greedy thought, I initially wanted to write the code as follows:
1 classSolution:2 #@return An integer as the maximum profit3 defMaxprofit (self, k, prices):4 ifPrices = = []:5 return06Down =Prices[0]7up =Prices[0]8Anslist = []9 forIinchRange (1, Len (Prices)):Ten ifPRICES[I-1] <Prices[i]: Oneup =Prices[i] A elifPrices[i] < Prices[i-1]: -Anslist.append (UP-Down ) -Down =Prices[i] theup =Prices[i] -Anslist.append (UP-Down ) -Anslist.sort (reverse=True) - ifK <Len (anslist): +Ans =sum (anslist[:k]) - Else: +Ans =sum (anslist) A returnans at -
And this greedy can be over:200/211 Test cases passed.
But think about it precisely because there are k restrictions, in fact, greed is wrong.
Consider this example:
"Not to be Continued"
"Leetcode" best time to Buy and Sell Stock IV