[leetcode]Best Time to Buy and Sell Stock III
来源:互联网 发布:数据脱敏的常用方法 编辑:程序博客网 时间:2024/05/22 20:45
class Solution {
public:
int maxProfit(vector<int> &prices) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if (prices.empty()) return 0;
int n = (int)prices.size();
vector<int> max_profit_before(n);
max_profit_before[0] = 0;
int min_price = prices[0];
for (int i = 1; i < n; i++) {
min_price = min(prices[i], min_price);
max_profit_before[i] = max(max_profit_before[i-1], prices[i] - min_price);
}
vector<int> max_profit_after(n);
max_profit_after[n - 1] = 0;
int max_price = prices[n - 1];
for (int i = n - 2; i >= 0; i--) {
max_price = max(prices[i], max_price);
max_profit_after[i] = max(max_profit_after[i+1], max_price - prices[i]);
}
int res = 0;
for (int i = 0; i < n; i++) {
res = max(res, max_profit_before[i] + max_profit_after[i]);
}
return res;
}
};
public:
int maxProfit(vector<int> &prices) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if (prices.empty()) return 0;
int n = (int)prices.size();
vector<int> max_profit_before(n);
max_profit_before[0] = 0;
int min_price = prices[0];
for (int i = 1; i < n; i++) {
min_price = min(prices[i], min_price);
max_profit_before[i] = max(max_profit_before[i-1], prices[i] - min_price);
}
vector<int> max_profit_after(n);
max_profit_after[n - 1] = 0;
int max_price = prices[n - 1];
for (int i = n - 2; i >= 0; i--) {
max_price = max(prices[i], max_price);
max_profit_after[i] = max(max_profit_after[i+1], max_price - prices[i]);
}
int res = 0;
for (int i = 0; i < n; i++) {
res = max(res, max_profit_before[i] + max_profit_after[i]);
}
return res;
}
};
- 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
- 音频编码介绍
- Linux 条件变量
- Linux文件写过程分析一(写过程中的锁)
- java中URL和File的相互转化
- 警惕通过数据库的破解取得操作系统管理员权限
- [leetcode]Best Time to Buy and Sell Stock III
- jquery中animate动画的小例子
- 字符串中出现的相同字母的个数
- jquery 操作checkbox
- <算法设计技巧与分析>M.H>Alsuwaiye编著 读书心得
- L2C码表的产生
- ClickOnce部署(2):自动更新
- 部落化的互联网生态,5个不同的思考维度
- 道德经之自胜者强