[Leetcode] best time to Buy and Sell Stock III @ Python

Source: Internet
Author: User

Original title address: https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/

Test instructions

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. You are in most of the transactions.

Note:
Engage in multiple transactions on the same time (ie, you must sell the stock before you buy again).

The idea of solving problems: the "low buy and sell high" rule in the trading market (buy lower and sell)

Only two trades are allowed, and the problem is much harder than the first two. The solution is ingenious, a bit of dynamic planning means:

Open two arrays P1 and P2,p1[i] represent the maximum profit for an exchange before Price[i],

P2[i] represents the maximum profit for an exchange after Price[i].

The maximum value of p1[i]+p2[i] is the maximum value required,

The calculations of P1[i] and p2[i] need to be dynamically planned, and it is not difficult to understand the code.

classSolution:#@param prices, a list of integers    #@return An integer    defMaxprofit (Self, prices): N=len (Prices)ifN <= 1:return0 P1= [0] *n P2= [0] *N MINV=Prices[0] forIinchRange (1, N): Minv= Min (Minv, prices[i])#Find low and buy lowP1[i] = max (p1[i-1], prices[i]-MINV) MAXV= Prices[-1]         forIinchRange (N-2,-1,-1): Maxv= Max (MAXV, Prices[i])#Find High and sell highP2[i] = max (p2[i + 1], MAXV-Prices[i]) Res=0 forIinchrange (N): Res= Max (res, p1[i] +P2[i])returnRes

[Leetcode] best time to Buy and Sell Stock III @ Python

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.