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;
}
本文介绍了一种寻找股票买卖最佳时机以获得最大利润的算法。该算法通过一次遍历价格数组,跟踪记录最低买入价及当前卖出所能获取的最大利润,最终返回最大利润值。
225

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



