您的位置:首页 > 其它

求股票的最大利润

2013-05-20 17:04 337 查看
给定表示股票具体价格的一序列数据(一个公司在某个市场的股票)。给定N天的数据序列,决定什么时候买入和卖掉能获得最大的利润。(假设只能买一只股票)。一只股票的价格在一天内不变,同一天不能同时买入和卖掉。

You have a sequence of data which tells about daily prices of a stock (of a company in some market). Given the sequence for N such days tell when should one buy and sell to maximize the profit. (for simplicity Assume you can buy only
1 stock). Prices of stock is same for a single day and you cannot buy and sell on the same day.

只能买卖一次。

Edit: You have to buy once only and sell once only. (I also misunderstood Q during interview that we have to tell sequence of buying and selling but it was not the question)

遍历价格序列,维护目前为止最低价格,使用a[i]-min更新最大利润,时间复杂度为O(n).

#include <vector>
using namespace std;
int maxProfit(vector<int>& a)
{
if (a.size() == 0)
{
return 0;
}
int min = a[0];
int max_Profit = 0;
int tmp = 0;
for (int i = 1;i<a.size();i++)
{
tmp = a[i] - min;
max_Profit = max(max_Profit,tmp);
if (a[i]<min)
{
min = a[i];
}
}
return max_Profit;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐