您的位置:首页 > 其它

算法练习(42):Best Time to Buy and Sell Stock II

2018-01-13 17:07 351 查看


题意:给出一个数组,每个数代表当天股票的价格,有无数次买卖股票的机会,但是持有时不能买另一个。问最大收益。

分析与思路:这道题设计到波峰波谷的概念,有两种思路。

1.可以每两个相邻的票价满足有收益都买(贪婪算法)

2.只买最近的极小值,只卖当前极小值后最近的极大值。

代码:

1.

class Solution {
public:
int maxProfit(vector<int>& prices) {
int sumPro = 0;
for (int i = 1; i < prices.size(); i++) {
if (prices[i] > prices[i - 1]) sumPro += prices[i] - prices[i - 1];
}
return sumPro;
}
};

2.
class Solution {
public:
int maxProfit(vector<int>& prices) {
int valley = 0, peak = 0;
int i = 0, sumPro = 0;
while (i < prices.size()) {
while (i + 1 < prices.size()&&prices[i] > prices[i + 1])i++;
valley = prices[i];
while (i + 1 < prices.size() && prices[i] < prices[i + 1]) i++;
peak = prices[i];
sumPro += (peak - valley);
i++;
}
return sumPro;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: