您的位置:首页 > 其它

[leetcode]: 122. Best Time to Buy and Sell Stock II

2017-05-03 17:03 148 查看

1.题目描述

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

翻译:一个数组表示一只股票n天的价格序列。求能够获得的最大收益。不限交易次数。但最多只能买一手,也就是必须先卖才能再买。

2.分析

把股票价格波动看做一段曲线,理想情况下,只要是价格上涨的阶段都是可以获得的收益。所以计算相邻价格差为正的和即可。

3.代码

python

def maxProfit(self, prices):
return sum([max(prices[i]-prices[i-1],0) for i in range(1,len(prices))])


我也真的是有点傻,把解题跟实际操作搞混了,所以自己写的时候是没有想到可以不管交易次数的(要手续费的嘛)。还是贴一下代码吧。

int maxProfit(vector<int>& prices) {
if (prices.empty())
return 0;
int low = prices[0];
int high = prices[0];
int profit = 0;
bool isbuy = false;
//在每个阶段最低点买入,最高点卖出
for (int i=1;i<prices.size();i++)
{
if (prices[i] >= prices[i - 1])//上涨或持平趋势
{
isbuy = true;//上涨就买并保持持有状态
high = prices[i];//记录最高位价格
}
else//下跌趋势
{
if (isbuy) {
profit += high - low;
isbuy = false;//卖出
}
low = prices[i];//记录最低位价格
}
}
if(isbuy)//最后买的一手在最后一天卖掉
profit += high - low;
return profit;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode stock profit