[leetcode] Best Time to Buy and Sell Stock III
2015-11-26 13:56
357 查看
题目:
分析:把数组一分为二,正序求最大值并保存到一个数组,然后反序求最大值并保存到另一个数组,最后这两个数组相加求最终最大值即可。
代码(可参考Best Time to Buy and Sell Stock):
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).
分析:把数组一分为二,正序求最大值并保存到一个数组,然后反序求最大值并保存到另一个数组,最后这两个数组相加求最终最大值即可。
代码(可参考Best Time to Buy and Sell Stock):
public int maxProfit(int[] prices) { if(prices == null || prices.length == 0) return 0; int[] result1 = new int[prices.length];//保存正序扫描的最大收益 int[] result2 = new int[prices.length];//保存反序扫描的最大收益 int min = prices[0], max = prices[0]; int result = 0; for (int i = 1; i < prices.length; i++) {//正序扫描 if (prices[i] > max) { // 实时计算并保存最大收益 max = prices[i]; if (max - min > result) { result = max - min; } } else if (prices[i] < min) { // 重新规定查找区域 min = prices[i]; max = prices[i]; } result1[i] = result; } min = prices[prices.length-1]; max = prices[prices.length-1]; result = 0; for (int i = prices.length-2; i >= 0; i--) {//反序扫描 if (prices[i] < min) { // 实时计算并保存最大收益 min = prices[i]; if (max - min > result) { result = max - min; } } else if (prices[i] > max) { // 重新规定查找区域 min = prices[i]; max = prices[i]; } result2[i] = result; } int max_profit = 0; for (int i = 0; i < prices.length; i++) {//叠加求和,输出最大值 if (result1[i] + result2[i] > max_profit) { max_profit = result1[i] + result2[i]; } } return max_profit; }
相关文章推荐
- lnmp 虚拟主机的配置
- eclipse和Mingw开发环境搭建
- 【转】深层次探讨mutex与semaphore之间的区别(下)
- RMI通讯2
- listView的adapter问题
- 如何把你的安卓手机变成Linux?
- VLFeat开源库
- Redis 安全漏洞检测攻击机防御
- 杭电acm2113
- 两款高性能并行计算引擎Storm和Spark比较
- JAVA经典实例
- Android常用动画
- UISlider用法详解
- 黑马程序员---Java基础篇之常见DOS命令讲解
- php类自动载入
- C++运算符重载
- 华为上机题:
- 用UIButton的titleEdgeInsets属性和 imageEdgeInsets属性实现图片文字按要求排列
- 移动硬盘安装linux系统小记
- iOS开发数据库篇—FMDB简单介绍