您的位置:首页 > 其它

股票最大收益 Best Time to Buy and Sell Stock II

2013-11-06 19:39 435 查看
题目源自于leetcode。

题目: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).

思路:假设这把这些点连起来看出折现,观察发现,获得最大收益的方法是每次都在极小值买入,在极大值卖出。

第一个点:如果一开始就在增长,则第一个点是极小值。

最后一点:如果最后是在增长,则最后一个点是极大值。

实际的代码中已经把两端的特殊情况包含在内了。

代码:

class Solution {
public:
int maxProfit(vector<int> &prices) {
int num = prices.size();
if(num <= 1)
return 0;

int sum =0;
int min, max;
int i=0;
while(i < num)
{
while((i+1<num) && (prices[i] > prices[i+1]))
i++;
min = prices[i];

while((i+1<num) && (prices[i] < prices[i+1]))
i++;
max = prices[i];

sum += max - min;
i++;
}
return sum;
}
};
注意:代码写完后要认真检查,返回值不能丢,变量初始化不能丢,输入合法性检查不能忘记。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: