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.
给定一个数组,数组位置i处的元素代表第i天的股价,求能获取的最大利润。
比较简单的题目,第i天可以取得的最大利润总是当天价格减去这一天之前的最小价格,用min遍历记录最小股价,max记录最大利润,一次遍历就可以求出结果。
AC code:
class Solution {
public:
int maxProfit(vector<int> &prices)
{
if(prices.size()==0)
return 0;
int min=prices[0],max=0; //min 最小价格 max 最大利润
for(int i=0;i<prices.size();i++)
{
if(min>prices[i])
min=prices[i];
if(max<prices[i]-min)
max=prices[i]-min;
}
return max;
}
}