best time to Buy and Sell Stock III

Source: Internet
Author: User

best time to Buy and Sell Stock III

Problem:

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.

Ideas:

Dynamic planning

My Code:

 Public classSolution { Public intMaxprofit (int[] prices) {        if(Prices = =NULL|| Prices.length <= 1)return0; intSize =prices.length; int[] left =New int[size]; int[] right =New int[size]; intMin = prices[0]; intmax = Prices[size-1]; intRST = 0;  for(intI=1; i<size; i++) {min=math.min (Min,prices[i]); Left[i]= Math.max (left[i-1],prices[i]-min); }         for(intj=size-2; j>=0; j--) {Max=Math.max (Max,prices[j]); RIGHT[J]= Math.max (right[j+1],max-Prices[j]); }         for(intk=0; k<size; k++) {rst= Math.max (rst, left[k]+Right[k]); }        returnrst; }}
View Code

The Learning Place:

    • For the dynamic planning problem, but also more and more feel, but also know how to find the dynamic programming equation, is nothing more than reverse thinking, but there are two dynamic planning methods are not familiar, such as the topic of this progressive way left[i-1]<=left[i]<=left[i+1] The other way to solve the optimal solution is to find the optimal solution of all the local optimal solutions.
    • For the problem that can not be thought out, should consider the following aspects, is there a rule? Can it be decomposed into several small problems, and then recursive solution or dynamic programming solution? Can you reduce the complexity of time by using the divide-and-conquer algorithm
    • Get rid of bad habits, life, thinking, etc.

best time to Buy and Sell Stock III

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.