Best Time to Buy and Sell Stock

来源:互联网 发布:淘宝店铺联盟怎么开通 编辑:程序博客网 时间:2024/05/29 14:55
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.

z这是一道dp问题。通过给定的整型数组选出买入和卖出的最大差值。

一开始没理解,以为遍历出一个最大值一个最小值就直接ok了。

理解题目出错了,因为如果输入的是[2,1]的话,这个最大收益是为0 的。

然后用两层for循环,每次找出该元素后面的最大元素,两者相减,保持最大差值。这样子是可以的,但是时间复杂度是N^2。判断超时。


看了提示,是DP。想想也是。

从后面往前面看,max(int[]a,start,end)=MAX{a[start],max(int[]a,start+1,end)};

就是某个元素后面最大值的最优子结构了。

算出这个最大值就能够直接算出该元素买入后能产生的最大收益,因此从尾往头算出max就能够直接算出最大收益了。

for(buyindex=a.length-1 to 0)

maxdiff(int[]a,int buyindex)=max(int[]a,buyindex,end)-a[buyindex];


上代码

public class Solution {    public int maxProfit(int[] prices) {        if(prices.length<=1)return 0;                int maxValue=-1;        int diff=0;        for(int indexpri=0;indexpri<prices.length;++indexpri){            if(maxValue<prices[prices.length-indexpri-1]){                maxValue=prices[prices.length-indexpri-1];            }            if(diff<maxValue-prices[prices.length-indexpri-1])            {                diff=maxValue-prices[prices.length-indexpri-1];            }        }        return diff;    }}


0 0