Best Time to Buy and Sell Stock
Say you have an array for which theithelement is the price of a given stock on dayi.
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.
考点:
和选最小值和最大值不同的是:需要先买后卖!
class Solution {
public:
int maxProfit(vector<int> &prices)
{
int buy = INT_MAX, profit = 0;
for (int i = 0; i < prices.size(); i++)
{
if (prices[i] < buy) buy = prices[i];
else profit = max(profit, prices[i]-buy);
}
return profit;
}
};
//2014-2-17 update
int maxProfit(vector<int> &prices)
{
int max_profit = 0;
int lowest_point = INT_MAX;
for (int i = 0; i < prices.size(); i++)
{
if (prices[i] < lowest_point) lowest_point = prices[i];
else max_profit = max(max_profit, prices[i]- lowest_point);
}
return max_profit;
}
本文介绍了一个算法问题,即如何确定股票的最佳买卖时机以获得最大利润。该问题要求只能进行一次交易,并提供了C++代码实现,通过跟踪最低购买价格并计算当前价格与最低购买价格之间的差值来更新最大利润。
677

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



