【LeetCode】Best Time to Buy and Sell Stock III
来源:互联网 发布:kali linux 使用教程 编辑:程序博客网 时间:2024/06/07 16:15
https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
这题没做出来,看了网上的分析才做出来的。。。关键点就是要利用on-line算法的性质,避免重复计算。
class Solution {public: int maxProfit(vector<int> &prices) { if (prices.size() < 2) { return 0; } vector<int> max_profile1; max_profile1.reserve(prices.size() + 1); // max_profile1[i] : max profit of [0, i] vector<int> max_profile2; max_profile2.reserve(prices.size() + 1); // max_profile2[i] : max profit of [i, end]; max_profile1[0] = 0; int low = prices[0], temp = 0; for (int i = 1, end = prices.size(); i < end; ++i) { if (prices[i] < low ) { low = prices[i]; } if (prices[i] - low > temp) { temp = prices[i] - low; } max_profile1[i] = temp; } max_profile2[prices.size()] = 0; int hi = prices[prices.size()-1]; temp = 0; for (int i = prices.size() - 1; i >= 0; --i) { if (hi < prices[i]) { hi = prices[i]; } if (temp < hi - prices[i]) { temp = hi - prices[i]; } max_profile2[i] = temp; } int max_profile = 0; for (vector<int>::size_type i = 0, end = prices.size(); i < end; ++i) { if (max_profile < max_profile1[i] + max_profile2[i+1]) { max_profile = max_profile1[i] + max_profile2[i+1]; } } return max_profile; }};
0 0
- LeetCode Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock III
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- leetcode 62: Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- 【leetcode】Best Time to Buy and Sell Stock III
- LeetCode - Best Time to Buy and Sell Stock III
- LeetCode之Best Time to Buy and Sell Stock III
- [LeetCode]Best Time to Buy and Sell Stock III
- LeetCode: Best Time to Buy and Sell Stock III
- [Leetcode]Best Time to Buy and Sell Stock III
- [leetcode]Best Time to Buy and Sell Stock III
- leetcode题目:Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- LeetCode-Best Time to Buy and Sell Stock III
- Mina-2.0.7源码学习 (1)
- Leetcode: Word Break
- Nt*和Zw*开头的函数
- linux命令 --mount
- 大数据图数据库之MapReduce用于图计算
- 【LeetCode】Best Time to Buy and Sell Stock III
- docker命令行
- jQuery_validate_js使用心得
- MD5算法的C++实现
- expdp/impdp 详细参数解释
- XML Handle by javax.xml.stream.*
- CentOS 卸载OpenJdk和Tomcat开机启动
- 黑马程序员-面向对象的基础1
- iOS开发所有KeyboardType与图片对应展示