Best time to buy and buy stock Total accepted:14044 Total submissions:45572 My submissions
Say you have an array for whichIThElement is the price of a given stock on dayI.
If you were only permitted to complete at most one transaction (ie, buy one and every one share of the stock ),
Design an algorithm to find the maximum profit.
Solution:
Greedy method:
Find the lowest price and the highest one day respectively, and the low price is higher. Note that the lowest day should be before the highest day.
Convert the original price sequence into a differential sequence,That isFor element J, the sold price at this point is equal to the minimum value of Prices [J] minus the element before it. In this way, it is OK to traverse the array.
This question can also be done in the largest M sub-segment and, M = 1.
Dynamic Planning:
First use Prices [I]-Prices [I-1] to convert the array to a differential sequence, then the problem is to find a maximum in this differential Sequence) can be solved using the leetcode -- maximum subarray maximum continuous subsequence and (Dynamic Planning) similar methods.
Note: If the hacker uses the method of profiteering cracking, the time complexity is O (n ^ 2), and the time limit is exceeded.
Program source code:
Greedy Algorithm Java code
Public int maxprofit (INT [] prices) {If (prices. length = 0) return 0; int I = 0; int profit = 0; int begmin = Prices [0]; for (I = 1; I <prices. length; ++ I) {profit = math. max (profit, Prices [I]-begmin); begmin = math. min (begmin, Prices [I]);} return profit ;}
Dynamic Planning: Java code
Public int maxprofit (INT [] prices) {int profit = 0; int temp = 0; For (INT I = 1; I <prices. length; ++ I) {int diff = Prices [I]-Prices [I-1]; temp = math. max (temp + diff, diff); profit = math. max (profit, temp);} return profit ;}
Profiteering cracking method:
/*** Profiteering enumeration method, exceeding the time limit * @ Param prices * @ return */public static int maxprofit2 (INT [] prices) {int profit = 0; for (INT I = 0; I <prices. length-1; ++ I) {for (Int J = I + 1; j <prices. length; ++ J) {profit = math. max (Prices [J]-Prices [I], profit) ;}} return profit ;}
Appendix:
Related questions:
Leetcode -- best time to buy and duplicate stock II (greedy strategy, differential sequence)
Leetcode -- best time to buy and dynamic stock III (Dynamic Planning)
Leetcode -- best time to buy and dynamic stock (greedy strategy or Dynamic Planning)