Best Time to Buy and Sell Stock:Say you have an array for which the i-th 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.
结题思路:相当于找数组中最大值和最小值之差,不过最大值出现在最小值之后。
代码如下:
<span style="font-family:KaiTi_GB2312;"> int maxProfit(vector<int>& prices) {
int size=prices.size();
if(size<=1)
return 0;
int minPrice=prices[0];
int maxProfit=prices[1]-prices[0];
for (int i=2;i<size;i++)
{
minPrice=min(prices[i-1],minPrice);
maxProfit=max(maxProfit,prices[i]-minPrice);
}
if(maxProfit<0)
return 0;
return maxProfit;
}</span>