Best Time to Buy and Sell Stock

来源:互联网 发布:泰格软件好用吗 编辑:程序博客网 时间:2024/05/29 18:50

1.题目

假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。

给出一个数组样例 [3,2,3,1,2], 返回 1

2.算法

动态规划,从前往后扫描,记录当前出现过的最低价格,作为买入价格,并计算以当天价格出售的收益,作为可能的最大收益

    public int maxProfit(int[] prices)     {        // write your code here        if (prices.length < 2)        {        return 0;        }        int curmin = prices[0];        int profit = 0;        for (int i = 1; i < prices.length; i++)        {        curmin = Math.min(curmin, prices[i]);        profit = Math.max(profit, prices[i] - curmin);        }        return profit;    }


0 0
原创粉丝点击