您的位置:首页 > 其它

Best Time to Buy and Sell Stock

2015-11-03 08:42 190 查看
题目:

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.

解析:

贪心法,分别找到价格最低和最高的一天,低进高出,注意最低的一天要在最高的一天之前。
把原始价格序列变成差分序列,本题也可以做是最大 m 子段和,m = 1。

class Solution
{
public:
int maxProfit(vector<int> &prices)
{
if (prices.size() < 2) return 0;
int profit = 0; // 差价,也就是利润
int cur_min = prices[0]; // 当前最小
for (int i = 1; i < prices.size(); i++)
{
profit = max(profit, prices[i] - cur_min);
cur_min = min(cur_min, prices[i]);
}
return profit;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: