LeetCode: Best Time to Buy and Sell Stock III
来源:互联网 发布:万网中文域名注册 编辑:程序博客网 时间:2024/05/20 11:35
思路:因为可以进行两次交易,而且每次交易不一定是在同一个单调区间内(不同于多次交易,如II )。
假设选择交易的分界点是 i 点(注意i点可以同时卖出、买进一次),只要知道i点左端的最大利率和右段的交易一次的最大利率,然后相加就是整个区间进行两次交易的最大利率,求解左右端利率的方法就是很基本的DP求解过程。
code:
class Solution {public: int maxProfit(vector<int> &prices) { int len = prices.size(); if(len == 0)return 0; int leftProfit[len], rightProfit[len]; memset(leftProfit,0,sizeof(int) * len); memset(rightProfit,0,sizeof(int) * len); int min_v = prices[0]; for(int i = 1;i <len;i++){ if(prices[i] < min_v) min_v = prices[i]; leftProfit[i] = leftProfit[i-1] > (prices[i] - min_v) ? leftProfit[i-1] : (prices[i] - min_v); } int max_v = prices[len-1]; for(int i = len-2;i >= 0;i--){ if(prices[i] > max_v) max_v = prices[i]; rightProfit[i] = rightProfit[i+1] > (max_v - prices[i]) ? rightProfit[i+1] : (max_v - prices[i]); } int maxProfit = 0; for(int i = 0;i < len;i++) maxProfit = std::max(maxProfit,rightProfit[i] + leftProfit[i]); return maxProfit; }};
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
- hadoop FS 命令(转)
- 关于多线程效率的思考
- iOS ARC机制 weak strong
- 淘宝海量数据产品技术架构
- hdu-2076-夹角有多大(题目已修改,注意读题)
- LeetCode: Best Time to Buy and Sell Stock III
- VBS获取天气预报[BY Broly]
- Java, ArrayList and Exception in thread “AWT-EventQueue-0” java.util.ConcurrentModificationException
- R: 控制台的清理与输出内容的保存 (Clear Console & Save Console Output)
- 详细介绍windows下使用python pylot进行网站压力测试
- 敏捷文档编制路线图
- Textviewb设置背景色失效
- Windows API函数大全
- 计算出表格里多行商品的总价