算法练习(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;
}
};
相关文章推荐
- 算法练习(38):Best Time to Buy and Sell Stock with Transaction Fee
- Leetcode Best Time to Buy and Sell Stock II OJ 刷题 算法
- 算法题——Best Time to Buy and Sell Stock II(JAVA)Greedy
- 算法(12)Best Time to Buy and Sell Stock II
- Leetcode练习-Best Time to Buy and Sell Stock II
- LeetCode编程练习 - Best Time to Buy and Sell Stock II学习心得
- Leetcode算法学习日志-122 Best Time to Buy and Sell Stock II
- 算法练习(37):Best Time to Buy and Sell Stock
- c++ leetcode 算法题 Best Time to Buy and Sell Stock II
- 【算法分析与设计】【第一周】121.&122. Best Time to Buy and Sell Stock I&II
- Best Time to Buy and Sell Stock II
- [leetcode]Best Time to Buy and Sell Stock I&II
- 【LeetCode】Best Time to Buy and Sell Stock II
- LeetCode122:Best Time to Buy and Sell Stock II
- LeetCode(42)-Best Time to Buy and Sell Stock(卖股票)
- leetcode之Best Time to Buy and Sell StockII
- Leetcode Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- [LeetCode]122 Best Time to Buy and Sell Stock II
- LeetCode-Best Time to Buy and Sell Stock II-解题报告