LeetCode 29 Best Time to Buy and Sell Stock III
来源:互联网 发布:在access数据库中 表是 编辑:程序博客网 时间:2024/05/15 16:13
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).
分析:
看到最大利润,首先想到动态规划;
动态规划,我们就要找子问题。
就此问题而言,两手交易,并且两手交易不能交叉,实际上是把数组分成两段,分别求前后两段的最大利润,
假设分割点是k,就是求[ 0, k ] 和 [ k, len-1] 的最大利润,注意,这里k是可以交叉的,因为题意是之多两手交易,如果刚好在k点卖出又买入,就可以认为总共进行了一手买卖。
这样,我们要分别计算每点的最大利润。
[0, k] 最大利润用一个动态规划,
[k, len-1] 最大利润用一个动态规划。
public class Solution { public int maxProfit(int[] prices) { if(prices==null || prices.length==0) return 0; int max=0; int[] left = new int[prices.length]; int[] right = new int[prices.length]; process(prices, left, right); for(int i=0; i<prices.length; i++) max = Math.max(max, left[i]+right[i]); return max; } private void process(int[] prices, int[] left, int[] right){ left[0]=0; int min=prices[0]; for(int i=1; i<left.length; i++){ left[i] = Math.max(left[i-1], prices[i]-min); min = Math.min(min, prices[i]); } right[right.length-1]=0; int max=prices[right.length-1]; for(int i=right.length-2; i>=0; i--){ right[i] = Math.max(right[i+1], max-prices[i]); max = Math.max(max, prices[i]); } }}
0 0
- LeetCode 29 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 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
- Linux - 判断文件/目录是否存在/具有权限
- jQuery插入,复制、替换和删除节点
- Ajax使用AntiForgeryToken,记录一下
- LeetCode OJ - Valid Number
- CentOS上编译安装OpenCV-2.3.1与ffmpeg-2.1.2
- LeetCode 29 Best Time to Buy and Sell Stock III
- 沁园春
- [编程好习惯] 精确包含头文件(转)
- WebLogic Enterprise JavaBean 编程
- java读取.properties配置文件的几种方法 .
- js正则表达式验证手机号,邮箱,QQ,密码
- VS.添加不了引用Microsoft.Office.Interop
- Python 希尔排序
- SecureCRT 常用命令