Best Time to Buy and Sell Stock III
来源:互联网 发布:今古传奇故事 知乎 编辑:程序博客网 时间:2024/05/21 14:45
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问题,能买2次(第一次的卖可以和第二次的买在同一时间),但第二次的买不能在第一次的卖左边。
利用left数组来存【0, i】的最大利润,每次需要保存左侧最小的价格min_price,然后left【i】= max(left【i-1】,prices【i】-min_prices)
然后再从右往左,利用right数组保存【i, n】的最大利润。每次需要保存右侧最大的价格max_price, 然后right【i】= max(right【i+1】,max_prices - prices【i】)
int maxProfit(vector<int> &prices){ if (prices.size() == 0) return 0; int profit = 0, n = prices.size(); int left[n], right[n]; memset(left, 0, sizeof(int) * n); memset(right, 0, sizeof(int) * n); int min_price = prices[0]; for (int i = 1; i < n; i++) { left[i] = max(prices[i] - min_price, left[i - 1]); min_price = min(prices[i], min_price); } int max_price = prices[n - 1]; for (int i = n - 2; i >= 0; i--) { right[i]= max(max_price - prices[i], right[i + 1]); max_price = max(prices[i], max_price); } for (int i = 0; i < n; i++) { profit = max(left[i] + right[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
- 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
- MYBATIS 的parameter
- HTTP和HTTPS详解
- 并行编程中的“锁”难题
- 素数筛选法
- 供应商常用标准表
- Best Time to Buy and Sell Stock III
- DataOutputStream and DataInputStream
- Oracle EBS供应商接口导入
- 10 PHP Apache函数(2)
- DM8168 layout
- OpenCV(C++接口)学习笔记2-像素级的图像操作
- adf开发出的table在IE8上面设置兼容性视图,导致显示标题和数据错位
- Uva 120 Stacks of Flapjacks
- 我们应该怎么做?