123. Best time to Buy and Sell Stock III
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).
Let's see if it's a trick or a big profit, but you're allowed to trade twice or you have to sell it before you buy it.
No idea. It's a little tricky.
Can you get the solution in the case of a traversal? Think about it, first.
How to feel this problem is good for stock ah. No idea at all.
or maintain a minimum and profit value after the transaction resets the minimum value while maintaining the maximum of two profit values?
No idea go to discuss area to see how the Great God solution--
PublicClassSolution {PublicIntMaxprofit(Int[] prices) {int hold1 = integer.min_value, hold2 = Integer.min_value;int release1 = 0, release2 = 0; For (int i:prices) { //Assume we only has 0 money at first release2 = Math.max (Release2, hold2+i); //The maximum if we ' ve just sold 2nd stock so far. Hold2 = Math.max (Hold2, release1-i); //The maximum if we ' ve just buy 2nd stock so far. Release1 = Math.max (release1, hold1+i); //The maximum if we ' ve just sold 1nd stock so far. Hold1 = Math.max (hold1,-i); //The maximum if we ' ve just buy 1st stock so far.} return release2; ///since Release1 is initiated as 0, so Release2 would always higher than Release1.}}
Space complexity O (1) time complexity O (n)
Understand each field hold1 the current maximum value of the first item hold2 buy the current maximum value of the second item release1 the current maximum value for the first item RELEASE2 sell the current maximum value of the second item
It's not a good idea. Decide to set up a case in eclipse and try it.
The given array is 2,5,8,3,18,12,6,53,59,11
public static void Main (string[] args) {test test =new test (); test. Solution Solution=test.new solution (); System.out.print (Solution.maxprofit (New int[]{2,5,8,3,18,12,6,53,59,11}));
The output result is
See how these four variables are changed in debug set breakpoints before Hold1
Read into the first number 2 no big changes
Read into the second number 5 release1 and release2 into 3
Omit some read to 18 o'clock look at each value
Release2 is the solution of the present stage ... I don't know how to do this first.
123. Best time to Buy and Sell Stock (iii) Leetcode problem-solving notes