best time to buy and sell stocks III
来源:互联网 发布:excel两个表格数据对比 编辑:程序博客网 时间:2024/05/22 12:55
对于这题,题目要求应该是最多交易两次
对于同一天内买进又卖出相当与没有参与交易
所以对于给出的一列数组【a1,a2,a3,...ai.....an】
可以分为两段在ai处,【a1....ai】的总利润+【a(i+1),...an】的利润=利润
将数组变成差分数组,分别求两段对应的利润
class Solution {public: int maxProfit(vector<int>& prices) { if (prices.size() < 2) return 0; const int n = prices.size(); vector<int> f(n, 0); vector<int> g(n, 0); for (int i = 1, valley = prices[0]; i < n; ++i) { valley = min(valley, prices[i]); f[i] = max(f[i - 1], prices[i] - valley); } for (int i = n - 2, peak = prices[n - 1]; i >= 0; --i) { peak = max(peak, prices[i]); g[i] = max(g[i], peak - prices[i]); } int max_profit = 0; for (int i = 0; i < n; ++i) max_profit = max(max_profit, f[i] + g[i]); return max_profit; }};
0 0
- [leetcode] best time to buy and sell stocks III
- best time to buy and sell stocks III
- Best Time to Buy and Sell Stocks
- LeetCode Best Time To Buy and Sell Stocks I II III IV
- [leetcode] best time to buy and sell stocks II
- [leetcode] best time to buy and sell stocks
- Best time to buy and sell stocks IV
- 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
- Best Time to Buy and Sell Stock III
- 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
- Best Time to Buy and Sell Stock III
- 快速排序(java实现)
- 第七周 项目2 友元类
- WebView.HitTestResult
- Dagger2 简单教程,一步一步教你怎么写!
- NAT、用iptables配置NAT
- best time to buy and sell stocks III
- 背包问题:01 完全 多重
- java中的条件运算符
- 算法与数据结构 - 0/1背包问题
- 矩阵的数乘次数
- LeetCode 20. Valid Parentheses
- opencv视频录制及解码器的一些说明
- 笔记练习:《Javascript入门经典(第5版)》page126_10.12_Practice
- JAVA之顺序表