best time to Buy and Sell Stock III solution

Source: Internet
Author: User

Question

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).

Solution

This problem can is solved by "divide and conquer". We can use Left[i] array to track maximum profit for transactions before I (including i), and Right[i + 1] to track Maximu M profit for Transcations after I.

Prices:1 4 5 7 6 3 2 9left = [0, 3, 4, 6, 6, 6, 6, 8]right= [8, 7, 7, 7, 7, 7, 7, 0]

Time complexity O (n), Space cost O (n).

1  Public classSolution {2      Public intMaxprofit (int[] prices) {3         if(Prices = =NULL|| Prices.length < 2)4             return0;5         intLength = prices.length, Min = prices[0], max = prices[length-1], Tmpprofit = 0;6         int[] Leftprofits =New int[length];7Leftprofits[0] = 0;8         int[] Rightprofits =New int[length];9Rightprofits[length-1] = 0;Ten         //Calculat left side profits One          for(inti = 1; i < length; i++) { A             if(Prices[i] >min) -Tmpprofit = Math.max (Tmpprofit, Prices[i]-min); -             Else theMin =Prices[i]; -Leftprofits[i] =Tmpprofit; -         } -         //Calculate right side profits +Tmpprofit = 0; -          for(intj = length-2; J >= 0; j--) { +             if(Prices[j] <max) ATmpprofit = Math.max (Tmpprofit, Max-prices[j]); at             Else -Max =Prices[j]; -RIGHTPROFITS[J] =Tmpprofit; -         } -         //Sum up -         intresult =Integer.min_value; in          for(inti = 0; i < length-1; i++) -result = Math.max (result, leftprofits[i] + rightprofits[i + 1]); toresult = Math.max (result, leftprofits[length-1]); +         returnresult; -     } the}

best time to Buy and Sell Stock III solution

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.