Best Time to Buy and Sell Stock leetcode java

愛做飯的小瑩子發表於2014-07-30

題目:

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

 

題解:

這道題只讓做一次transaction,那麼就需要找到價格最低的時候買,價格最高的時候賣(買價的日期早於賣價的日期)。從而轉化為在最便宜的時候買入,賣價與買價最高的賣出價最大時,就是我們要得到的結果。

因為我們需要買價日期早於賣價日期,所以不用擔心後面有一天價格特別低,而之前有一天價格特別高而錯過了(這樣操作是錯誤的)。

所以,只許一次遍歷陣列,維護一個最小買價,和一個最大利潤(保證了買在賣前面)即可。

程式碼如下:

 

1     public int maxProfit(int[] prices) {
2         int min = Integer.MAX_VALUE,max=0;
3         for(int i=0;i<prices.length;i++){
4             
5             min=Math.min(min,prices[i]);
6             max=Math.max(max,prices[i]-min);
7         }
8         return max;
9     }

相關文章