[LeetCode] Best Time to Buy and Sell Stock III
来源:互联网 发布:c语言点餐系统 编辑:程序博客网 时间:2024/05/16 06:55
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 maxProfit(vector<int> &prices) { int n = prices.size(), profit = 0; if(n == 0) return 0; int l[n], r[n]; memset(l, 0, sizeof(int) * n); memset(r, 0, sizeof(int) * n); int min = prices[0]; for(int i = 1; i < n; i++) { l[i] = prices[i] - min > l[i - 1] ? prices[i] - min : l[i - 1]; min = prices[i] < min ? prices[i] : min; } int max = prices[n - 1]; for(int i = n - 2; i >= 0; i--) { r[i] = max - prices[i] > r[i + 1] ? max - prices[i] : r[i + 1]; max = prices[i] > max ? prices[i] : max; } for(int i = 0; i < n; i++) profit = l[i] + r[i] > profit ? l[i] + r[i] : profit; return profit; }};
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
- [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
- UVA 10453 Make Palindrome(区间简单DP)
- 笔记之Prolog
- MySQL报错处理
- python 安装django
- native wifi mac rssi
- [LeetCode] Best Time to Buy and Sell Stock III
- 大道至简 悟在天成
- firefox 扩展开发技巧
- cocos2dx 在mac下开发ios和android游戏
- 汇编转移指令的原理
- cocos2d-x3.0 Slider
- Probability 2131
- Struts2整合Spring的两种方式
- Cocos2dx 小技巧(十一) 小人虽短,但可以旋转