Best Time to Buy and Sell Stock III
来源:互联网 发布:python 贝叶斯分类器 编辑:程序博客网 时间:2024/06/06 07:23
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
class Solution {public: int max(vector<int>& prices, int s, int e) { if (s >= e) return 0; int ret = 0; int min = prices[s]; for (int i = s + 1; i <= e; i++) { if (prices[i] < min) min = prices[i]; else if (prices[i] - min > ret) { ret = prices[i] - min; } } return ret; } int maxProfit(vector<int> &prices) { if (prices.size() <= 1) return 0; int ret = 0; for (int i = 0; i < prices.size(); i++) { int cur = max(prices, 0, i) + max(prices, i, prices.size() - 1); ret = ret > cur ? ret : cur; } return ret; }};第二次通过,利用动态规划时间复杂度O(n),逆序遍历与顺序不同的是,逆序是记录最大值并于当前值比较,顺序是记录最小值,并与当前值比较
class Solution {public: int maxProfit(vector<int> &prices) { if (prices.size() <= 1) return 0; int N = prices.size(); vector<int> dp; int min = prices[0]; dp.push_back(0); for (int i = 1; i < N; i++) { min = min > prices[i] ? prices[i] : min; int tmp = prices[i] - min; dp.push_back(tmp > dp[i-1] ? tmp : dp[i-1]); } int max = prices[N - 1]; int maxProf = 0; int ret = 0; for (int i = N-2; i >= 0; i--) { max = max > prices[i] ? max : prices[i]; maxProf = maxProf > max - prices[i] ? maxProf : max - prices[i]; ret = ret > maxProf + dp[i] ? ret : maxProf + dp[i]; } return ret; }};
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
- 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
- 【leetcode】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
- 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]Best Time to Buy and Sell Stock III
- Linux 之Cut命令详解
- QQ通信原理及QQ是怎么穿透内网进行通信的?
- zoj-3772-Calculate the Function-线段树+矩阵
- Pascal's Triangle
- Pascal's Triangle II
- Best Time to Buy and Sell Stock III
- 《汇编语言》第一章-基础知识
- LeetCode (Word Break II )
- 如何在GNU/Linux操作系统中使用命令行xdg-open打开一个任意格式的文件
- Word Ladder II -- LeetCode
- 知乎网站2010年12月开放,三个月后获得了李开复的天使投资
- shell变量数学运算
- Symmetric Tree -- LeetCode
- LeetCode(Copy List with Random Pointer) 复杂链表的深拷贝