Best Time to Buy and Sell Stock III
来源:互联网 发布:股票预测软件破解 编辑:程序博客网 时间:2024/06/04 23:27
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).
这里很容易就想到 用数组 l[i] r[i]分别表示0~i,i+1~n中最大的profit。然后分别计算数组l、r,这样的算法复杂度是O(n^2)
然而有O(N)的算法。
在我们计算l[i+1]的时候,跟l[i]是有关系的。0~i+1最大的利润等于即0~i最大的利润、prices[i+1]-min中的较大者。同样可以求解r[i]
class Solution {public: int maxProfit(vector<int> &prices) { int n = prices.size(); if(n==0) return 0; int l[n]; int r[n]; memset(l,0,sizeof(int)*n); memset(r,0,sizeof(int)*n); int min1 = prices[0]; for(int i = 1 ;i<n;i++) { l[i] = prices[i]-min1 > l[i-1]?prices[i]-min1:l[i-1]; min1 = min(min1,prices[i]); } int max1 = prices[n-1]; for(int i = n-2;i>=0;i--) { r[i] = max1-prices[i] > r[i+1] ? max1-prices[i] : r[i+1]; max1 = max(max1,prices[i]); } int ans = 0; for(int i = 0;i<n;i++) { if(l[i]+r[i]>ans) ans = l[i]+r[i]; } return ans; }};
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
- 无尽弹珠
- OSI七层协议和TCP/IP四层协议之比较
- QT5.3.2+mingw静态编译(生成exe大约14M)
- 如何优雅的管理游戏资源
- View.VISIBLE、INVISIBLE、GONE的区别
- Best Time to Buy and Sell Stock III
- gluLookAt
- 软件开发和团队”最小模式”初探2-6人模型
- Convert Sorted Array to Binary Search Tree
- 提升工作效率的软件(大众版) by Mr. Niebieski
- Eclipse设置编辑器中的字体为Courier New
- 【算法导论】中位数和顺序统计量之选择算法
- 文本框输入监控事件
- OCILIB使用事务