First: Test instructions is the stock price of a stock in an array. The first I is the price of the first day. The most profitable. Allowed to buy and sell once
The problem is to ask for the maximum difference. You can record the minimum value and then, based on the minimum value, find the current maximum difference.
Public classSolution { Public intMaxprofit (int[] prices) { if(prices.length==0| | Prices.length==1) { return0; } intLow=prices[0],ans=0; for(inti=1;i<prices.length;i++) { if(Low>prices[i]) low=Prices[i]; Record minimum valueElse { if(prices[i]-low>ans) {ans= prices[i]-Low ; } } } returnans; }}
Second: Test instructions allows multiple transactions on the basis of the first question. But you must buy and sell, not buy or sell continuously.
The problem is to ask for the sum of all the difference values. You can imagine a stock price as a line chart. Adding the difference of all ascending segments is the result.
Public classSolution { Public intMaxprofit (int[] prices) { if(prices.length==0| | Prices.length==1) { return0; } intLow = Prices[0]; intHigh = 0; intsum = 0; for(inti = 1;i<prices.length;i++) { if(low>prices[i])//If the current stock price is below the minimum value, low suction=Prices[i]; } Else { if((i<prices.length-1) && (prices[i+1]>Prices[i])) If the subsequent value is larger than the current value (still in the ascending phase) {Continue; } else//If it is currently a peak, sell the stock{sum= sum+prices[i]-Low ; Low=Prices[i]; } } } returnsum; }}
Leetcode-best time to Buy and Sell Stock i&&ii