您的位置:首页 > 其它

Best Time to Buy and Sell Stock

2013-10-17 02:33 267 查看
Objective:

Find out the lowest point to buy-in and find out the a following hightest point to sell-out. And the maximal profit is equivalent to the max difference between the highest point and lowest point.

Before solving this problem, suggest referring to the "maximum subarray" first. Then you will get an idea how to set the pointer and how to store the "buy" and "sell" variables.

class Solution {

public:
int maxProfit(vector<int> &prices) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if (prices.empty()) return 0;
int cur = 0; // the pointer
int buy = 0; // date to buy
int sell = 0; // day to sell
int maxProf = 0; // the maximum profit

for(int i=1;i<prices.size();i++)
{
if(prices[i]<prices[cur])
cur = i;
else if(prices[i]>prices[cur] && prices[i]-prices[cur]>maxProf)
{
buy = cur;
sell = i;
maxProf = prices[i]-prices[cur];
}

}

return maxProf;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: