[leedcode 121] Best Time to Buy and Sell Stock

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.

public class Solution {
    public int maxProfit(int[] prices) {
        //本题也是求右边数减左边数最大的差问题,遍历时,需要保存最小值,然后每一个值和最小值相减,保存最大中间结果
        if(prices.length<=1) return 0;
        int min=prices[0];
        int res=0;
        for(int i=1;i<prices.length;i++){
             res=Math.max(res,prices[i]-min);
             min=Math.min(min,prices[i]);
        }
        return res;
        
    }
}

 

posted @ 2015-07-23 23:35  ~每天进步一点点~  阅读(116)  评论(0编辑  收藏  举报