Best Time to Buy and Sell Stock III
来源:互联网 发布:pc蛋蛋幸运28算法公式 编辑:程序博客网 时间:2024/05/21 05:59
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).
思路:DP的思路,分别记录每个位置到目前为止的最大收益。从左边扫描一遍,每个位置记录的为这之前如果进行第一次交易的最大受益;再从右边扫描一遍,记录当前位置之后如果进行第二次交易的最大受益。然后取左右求和取最大值即可。
class Solution {public: int maxProfit(vector<int> &prices) { int size = prices.size(); if (size <= 1) { return 0; } vector<int> profit_left(size, 0); vector<int> profit_right(size + 1, 0); int low = prices[0]; int maxProfit = 0; for (int i = 1; i < size; i++) { profit_left[i] = max(profit_left[i - 1], prices[i] - low); if (prices[i] < low) { low = prices[i]; } } int high = prices[size-1]; for (int i = size - 2; i >= 0; i--) { profit_right[i] = max(profit_right[i + 1], high - prices[i]); if (prices[i] > high) { high = prices[i]; } } for (int i = 0; i < size; i++) { maxProfit = max(maxProfit, profit_left[i] + profit_right[i]); } return maxProfit; }};
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 Shell保存当前路径
- SQLite3第三方库之FMDB
- .htaccess没有生效的解决
- 织梦DEDECMS时间标签调用格式大全
- AJAX - onreadystatechange 事件
- Best Time to Buy and Sell Stock III
- mysql root密码找回
- adb配置
- Android中使用apache commons-net发送后台邮件的方法
- Android下的布局
- Java中文件的上传与下载
- angularjs directive semantic-ui pagination
- angularjs route 中的用户身份认证
- angularjs 利用 service + $broadcast 在多个controllers 之间共享数据