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
1:遍历数组;2:每一个数字获得该数字之前的最小的数字,并与当时保存的最大值相比较
int maxProfit(vector<int> &prices)
{
if(prices.size() <= 1)
{
return 0;
}
int maxValue = 0;
int minPrice = prices[0];
int size = (int)prices.size();
for(int i = 1; i < size; i++)
{
if(prices[i] > minPrice)
{
maxValue = (maxValue > prices[i] - minPrice ? maxValue : prices[i] - minPrice);
}
else
{
minPrice = prices[i];
}
}
return maxValue;
}

本文介绍了一种寻找股票买卖最佳时机以实现最大利润的算法。该算法通过一次遍历数组来确定买入最低价并计算可能的最大收益。适用于仅允许进行一次交易的情况。
681

被折叠的 条评论
为什么被折叠?



