[Leetcode]Best Time to Buy and Sell Stock II
2013-06-21 10:46
441 查看
我们知道Best Time to Buy and Sell Stock的思路是:Find i and j that maximizes Aj - Ai,
where i < j,而II中对交易的次数没有限制,我们要做的是找到多对<Ai,Aj>且(Ai,Aj)都互不重叠。我们知道最优解中的每对Ai和Aj肯定是该区间的最值(反证法可以得到)。似乎没有很好的办法来求解。
我们知道对于一个区间的最值之差Aj-Ai,我们可以依次想减前后两个值,然后累加即可,扫描整个数组得到的正是我们想要的答案。
where i < j,而II中对交易的次数没有限制,我们要做的是找到多对<Ai,Aj>且(Ai,Aj)都互不重叠。我们知道最优解中的每对Ai和Aj肯定是该区间的最值(反证法可以得到)。似乎没有很好的办法来求解。
我们知道对于一个区间的最值之差Aj-Ai,我们可以依次想减前后两个值,然后累加即可,扫描整个数组得到的正是我们想要的答案。
class Solution { public: int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function int ans = 0; for(int i = 1; i < prices.size(); ++i) ans += max(0, prices[i] - prices[i-1]); return ans; } };
相关文章推荐
- LeetCode 122: 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] Best Time to Buy and Sell Stock II
- 【LeetCode】 best-time-to-buy-and-sell-stock-i ii iii iv
- [leetcode] Best Time to Buy and Sell Stock II
- [LeetCode9]Best Time to Buy and Sell Stock II
- LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
- LeetCode(122) Best Time to Buy and Sell Stock II (Java)
- LeetCode: 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 I && II && III && IV
- Leetcode练习-Best Time to Buy and Sell Stock II
- Leetcode 122 Best Time to Buy and Sell Stock II
- LeetCode-122-Best Time to Buy and Sell Stock II-E
- LeetCode-122: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] Best Time to Buy and Sell Stock II 贪心算法
- Best Time to Buy and Sell Stock II ——LeetCode