Say you have an array for which theithelement is the PRice of a given stock on dayi.
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.
這道題就不僅僅只是算法題了,我們還要考慮到生活中的常識。
比如這個是Buy and Sell,就說明我們必須是先Buy然后再Sell。
比如第五天價格最低,第三天價格最高,我們肯定不能第五天買了然后穿越回去第三天賣出去啊。所以loop的時候要考慮到這些因素。
代碼如下。~
public class Solution { public int maxProfit(int[] prices) { //special case if(prices==null||prices.length<2){ return 0; } int min=prices[0]; int profit=0; for(int i=0;i<prices.length;i++){ if(profit<(prices[i]-min)){ profit=prices[i]-min; }else if(prices[i]<min){ min=prices[i]; } } return profit; }}新聞熱點
疑難解答