First, the topic
1, examining
2. Analysis
Given an array of daily prices for a stock, you can trade multiple times to find out how big the profit is.
Second, the answer
1, Ideas:
Method One,
Seek the maximum profit, from the back to the front, if the current price to sell, the day before the price of buy, you can complete the transaction, and gain profits. Finally, all profits can be counted.
Public int maxProfit11 (int[] prices) { int total = 0; for (int i = 1; i < prices.length; i++) { if(Prices[i] > prices[i-1]) + = prices[i]-prices[i-1] ; } return Total ; }
Method Two,
①, first finds the Min min from the current position until the next number is larger than Min, and records this minimum min.
②, from min after the maximum number from the current start Max, until it encounters a smaller than the previous number, then record this maximum max.
③, Max-min is a profit trading, continue to search backwards.
Public intMaxprofit (int[] prices) { intProfit = 0, i = 0; intLen =prices.length; while(I <Len) { while(I < len-1 && prices[i + 1] <=Prices[i]) I++; intMin = prices[i++]; while(I < len-1 && prices[i + 1] >=Prices[i]) I++; Profit+ = i < Len? prices[i++]-min:0; } returnprofit; }
122. Best time to Buy and Sell Stock II