1. 程式人生 > >Array——LeetCode——Best Time to Buy and Sell Stock II

Array——LeetCode——Best Time to Buy and Sell Stock II

price time [] turn pan 價格 pri tmp span

【學到的知識點——】

-----------------------------------------------------------------------------------------------------
【反思】
1、max每次都加自己。
-----------------------------------------------------------------------------------------------------
【別人的Java解法代碼】

-----------------------------------------------------------------------------------------------------
【自己的Java解法代碼】

 1     public  static int maxProfit(int[] prices) {
 2         int max = 0;
 3         int tmpMax = 0;
 4         int tmp = 0;                                        //當前股票最低價格
 5         if (prices.length != 0 && prices != null) {
 6              tmp = prices[0];
 7          }
 8         for (int
i = 1; i < prices.length; i++) { 9 if (prices[i] >= prices[i-1]) { //股價持續上漲,或者持平,不賣出 10 if (i == prices.length - 1) { 11 //收盤價格 12 tmpMax = prices[i] - tmp; 13 max = tmpMax + max; 14 }
15 } else { //股價下降 16 tmpMax = prices[i-1] -tmp; 17 tmp = prices[i]; 18 max = tmpMax + max; 19 } 20 } 21 return max; 22 }

Array——LeetCode——Best Time to Buy and Sell Stock II