"Leetcode" best time to Buy and Sell Stock IV

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.