[Leetcode 123, Hard] Best Time to Buy and Sell Stock III
来源:互联网 发布:端口的作用是什么 编辑:程序博客网 时间:2024/05/29 09:09
Problem:
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Analysis:
Solutions:
C++:
int maxProfit(vector<int> &prices) { if(prices.size() <= 1) return 0; int max_left = 0; vector<int> maxs_from_left; maxs_from_left.push_back(0); int min_price = prices[0]; for(int i = 1; i < prices.size(); ++i) { if(min_price > min(prices[i - 1], min_price)) min_price = prices[i - 1]; if(max_left < prices[i] - min_price) max_left = prices[i] - min_price; maxs_from_left.push_back(max_left); } int max_two_trans = maxs_from_left[maxs_from_left.size() - 1]; int max_price = prices[prices.size() - 1]; for(int i = prices.size() - 2; i >= 1; --i) { if(max_price < max(max_price, prices[i])) max_price = prices[i]; if(max_two_trans < maxs_from_left[i - 1] + max_price - prices[i]) max_two_trans = maxs_from_left[i - 1] + max_price - prices[i]; } return max_two_trans; }Java:
Python:
0 0
- [Leetcode 123, Hard] Best Time to Buy and Sell Stock III
- LeetCode 123: Best Time to Buy and Sell Stock III
- LeetCode: Best Time to Buy and Sell Stock III [123]
- LeetCode 123 Best Time to Buy and Sell Stock III
- [leetcode 123] Best Time to Buy and Sell Stock III
- leetcode || 123、Best Time to Buy and Sell Stock III
- leetcode-123 Best Time to Buy and Sell Stock III
- leetcode 123: Best Time to Buy and Sell Stock III
- 123 Best Time to Buy and Sell Stock III [Leetcode]
- Best Time to Buy and Sell Stock III - LeetCode 123
- LeetCode 123: Best Time to Buy and Sell Stock III
- LeetCode 123 Best Time to Buy and Sell Stock III
- LeetCode 123 -- Best Time to Buy and Sell Stock III
- Leetcode 123 Best Time to Buy and Sell Stock III
- LeetCode 123 Best Time to Buy and Sell Stock III
- Leetcode Best Time to Buy and Sell Stock III 123
- [Leetcode 123] Best Time to Buy and Sell Stock III
- **Leetcode 123 Best Time to Buy and Sell Stock III
- LeetCode #20 Valid Parentheses
- 如何修改mysql配置中的字符集
- Best time to buy and sell stocks IV
- 乒乓球教程
- 斯坦福《机器学习》Lesson5感想———1、成学习算法
- [Leetcode 123, Hard] Best Time to Buy and Sell Stock III
- Objective-C对象与Core Foundation对象
- Java I/O 详解
- Android提高(17)——第一章 Http基础详解
- hdu 5305 Friends 【暴搜】
- 关于HTML和CSS的学习心得
- oracle断开用户连接并且重新创建用户
- hdu5289RMQ求区间最大最小值和单调队列维护区间最大最小值
- ARM上的浮点运算