標籤:leetcode
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.
原題連結:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/
題目:假設你有一個數組,其中的第 i 個元素代表給定的第 i 天的股票價格。
如果你被允許至多完成一個交易(如,買一和賣一股票),設計一個演算法找出最大的利潤。
最Naive的解法,就是遍曆所有的 後 - 前 ,找出最小值。逾時了。
public static int maxProfit(int[] prices){int len = prices.length;if(len <= 1)return 0;int max = 0;for(int i=0;i<len;i++){for(int j=i+1;j<len;j++){int profit = prices[j] - prices[i];if(max < profit)max = profit;}}return max;}
下面的方法就簡便多了,首先賦首元素的值給最小,依次向後計算利潤,每次與最大值比較並儲存新的最大值和新的最小值。
public static int maxProfit(int[] prices){int len = prices.length;if(len <= 1)return 0;int min = prices[0],max = 0;for(int i=1;i<len;i++){int profit = prices[i] - min;if(max < profit)max = profit;if(min > prices[i])min = prices[i];}return max;}