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.
这道题就不仅仅只是算法题了,我们还要考虑到生活中的常识。
比如这个是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; } }