Best Time to Buy and Sell Stock III 解答
2015-09-21 07:23
375 查看
Question
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).
Solution
This problem can be solved by "divide and conquer". We can use left[i] array to track maximum profit for transactions before i (including i), and right[i + 1] to track maximum profit for transcations after i.Prices: 1 4 5 7 6 3 2 9 left = [0, 3, 4, 6, 6, 6, 6, 8] right= [8, 7, 7, 7, 7, 7, 7, 0]
Time complexity O(n), space cost O(n).
public class Solution { public int maxProfit(int[] prices) { if (prices == null || prices.length < 2) return 0; int length = prices.length, min = prices[0], max = prices[length - 1], tmpProfit = 0; int[] leftProfits = new int[length]; leftProfits[0] = 0; int[] rightProfits = new int[length]; rightProfits[length - 1] = 0; // Calculat left side profits for (int i = 1; i < length; i++) { if (prices[i] > min) tmpProfit = Math.max(tmpProfit, prices[i] - min); else min = prices[i]; leftProfits[i] = tmpProfit; } // Calculate right side profits tmpProfit = 0; for (int j = length - 2; j >= 0; j--) { if (prices[j] < max) tmpProfit = Math.max(tmpProfit, max - prices[j]); else max = prices[j]; rightProfits[j] = tmpProfit; } // Sum up int result = Integer.MIN_VALUE; for (int i = 0; i < length - 1; i++) result = Math.max(result, leftProfits[i] + rightProfits[i + 1]); result = Math.max(result, leftProfits[length - 1]); return result; } }
相关文章推荐
- 122 Best Time to Buy and Sell Stock II [Leetcode]
- 项目进度估算难题
- 121 Best Time to Buy and Sell Stock [Leetcode]
- Android 动画——Layout Animations布局动画
- LeetCode Generate Parentheses
- 品牌为什么爱推定制机
- session的存储方式和配置
- Linux服务管理之httpd-2.4常用配置及phpMyAdmin的安装配置
- ASP.NET页面之间传递值的几种方式
- 读《大道至简—编程的精义》有感
- 数据结构-线性表链式表示
- 《大道至简》第一章读后感
- 当前项目中,linux下memcached的启动/结束的方式
- CUDPP基本执行过程分析
- viewpager不显示
- 写几十行代码,来一场无鼠标编程之旅,看看who is e———(HTML5:HBuilder5.0.0)
- 在win7系统的电脑上安装CentOS7双系统
- 2015年9月14日--9月20日(30小时,剩3485小时)
- UIPercentDrivenInteractiveTransition Controller交互式转场切换动画
- 新的开始