121. Best Time to Buy and Sell Stock

来源:互联网 发布:卫星电视直播软件apk 编辑:程序博客网 时间:2024/06/05 05:36

题目:

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 int maxProfit(int[] prices) {//        local表示直到今天的利润 local=Math.max(prices[i]-prices[i-1]+local,0);//        global表示直到今天最大利润 global = Math.max(local,global);        if(prices==null || prices.length==0)            return 0;        int global = 0;        int local = 0;        for(int i=1;i<prices.length;i++)        {            local=prices[i]-prices[i-1]+local>0?prices[i]-prices[i-1]+local:0;            global=local>global?local:global;        }        return global;    }
原创粉丝点击