Best Time to Buy and Sell Stock III
来源:互联网 发布:青年网络公开课全集 编辑:程序博客网 时间:2024/05/16 19:53
Say you have an array for which the ith element is the price of a given stock on dayi.
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).
这个题的原型:http://blog.csdn.net/huruzun/article/details/39429631 利用动态规划思想,因为是最多两次交易,用一个数组记录左边每个位置profit 另外一个右边位置profit
数组l[i]记录了price[0..i]的最大profit,
数组r[i]记录了price[i..n]的最大profit。
已知l[i],求l[i+1]是简单的,同样已知r[i],求r[i-1]也很容易。
最后,我们再用O(n)的时间找出最大的l[i]+r[i],即为题目所求。
public class Solution { public int maxProfit(int[] prices) { if (prices == null || prices.length == 0) { return 0; } int n = prices.length; int[] left = new int[n]; int[] right = new int[n]; int min = prices[0]; for (int i = 1; i < n; i++) { left[i] = left[i - 1] > prices[i] - min ? left[i - 1] : prices[i] - min; min = min < prices[i] ? min : prices[i]; } int max = prices[n - 1]; for (int i = n - 2; i >= 0; i--) { right[i] = right[i + 1] > max - prices[i] ? right[i + 1] : max - prices[i]; max = max > prices[i] ? max : prices[i]; } int value = 0; for (int i = 0; i < n; i++) { value = value > left[i] + right[i] ? value : left[i] + right[i]; } return value; }}
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
- 求一个数是否为完数
- Ubuntu14.04无法开机“为/检查磁盘时发现严重错误”
- 用数学方法+数学软件去做一个物理题~
- hdu 5024 Wang Xifeng's Little Plot 2014 ACM/ICPC Asia Regional Guangzhou Online dfs
- MATLAB——fix,round,ceil 函数
- Best Time to Buy and Sell Stock III
- 实验一报告
- 错误 101 (net::ERR_CONNECTION_RESET):连接已重置
- viso 2013 网格背景
- 我心目中理想的软件开发过程
- CSS选择器
- android adt bundle gradle打包错误
- Maven使用总结
- HDU 5024 Wang Xifeng's Little Plot(2014广州网络赛1003)