Leetcode - Best Time to Buy and Sell Stock

来源:互联网 发布:淘宝修改我的评价 编辑:程序博客网 时间:2024/06/10 21:58

Question

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.


Java Code

public int maxProfit2(int[] prices) {    int len = prices.length;    if(len < 2) return 0;    int max = 0;    int buy = prices[0];    int[] maxEarning = new int[len];    maxEarning[0] = 0;    for(int i = 1; i < len; ++i) {        //计算当前天卖出股票的收益,并比较得到全局的最大收益max        if((maxEarning[i] = prices[i] - buy) > max)            max = maxEarning[i];        //更新股票的历史最低报价,作为买入的价格buy        if(prices[i] < buy)            buy = prices[i];    }    return max;}

说明

  • 本题看似是一个很简单的问题,本质上就是求价格曲线的极大值与极小值之差,且要求极大值必须出现在极小值之后,即股票以最低价买入最高价卖出所得的收益才是最大,但是这里股票价格是一系列离散的点,无法用连续函数的导数求出极值,只能逐个点进行比较。如果使用动态规划的思想来解决这个问题就显得比较容易了,其状态转移关系是,当前天的收益等于当天的股票报价减去历史最低报价,所以只需要一直更新历史最低报价就行,则股票的全局最大收益就是所有天收益中的最大值。
0 0
原创粉丝点击