leetcode中的股票问题(1)
最近股市比较吸引眼球,而正好刷到了leetcode中股票问题,啥都不说了,我们来一起探讨探讨。
https://leetcode.com/problems/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.
翻译:有一个
问题分析
先来张图直观的理解一下:
凭直觉,不难发现我们要找的其实是:
这一手交易可以赚9-2 =7元钱,直观的感受当然是拿最高的票价减去最低的票价。但是可以看出,12号的票价是最低的,为1元,但是却没有用,因为虽然可以以1元的价格买入,但其后并没有很高的价格可以卖出了,很可惜~
也就是说,高价出现在低价后面才有意义,说白了无非是要找两个数值:买入的那一天
假设我们分析在第i天卖出所能获得的最大收益,则必然是
price(i)−min(i)>0?price(i)−min(i):0
这里我们约定
min(i)
表示第i天之前的最低价,当然如果第i天之前最小的股价都比第i天大,那在这一天卖出只能亏钱咯,而题目中说at most one transaction所以买卖不做咯。
然后的想法就简单啦,我们从做到右扫一遍,记录在每天卖出的最大收益,用一个标记来维护最大值就行啦~~~
代码
public int maxProfit(int[] prices) {
//less then two days, no game
if(prices.length < 2)
{
return 0;
}
//tag to maintian the min price
int leastTag = prices[0];
//tag to maintian the max profit
int profit = 0;
for(int i = 1; i < prices.length; i++)
{
if( prices[i] - leastTag > profit)
{
profit = prices[i] - leastTag;
}
//else means price[i] < profit + leastTag
//but not necessarily price[i] < leastTag
else if(prices[i] < leastTag)
{
leastTag = prices[i];
}
}
return profit;
}
今天就到这里咯,明天来玩股票的2、3、4题