188. Best time to Buy and Sell Stock IV leetcode Python

Source: Internet
Author: User

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

Related Article

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.