【LintCode】 Best Time to Buy and Sell Stock III 买卖股票的最佳时机 III
2015-07-30 10:05
489 查看
假设你有一个数组,它的第i个元素是一支给定的股票在第i天的价格。设计一个算法来找到最大的利润。你最多可以完成两笔交易。
样例
给出一个样例数组 [4,4,6,1,1,4,2,5], 返回 6
注意
你不可以同时参与多笔交易(你必须在再次购买前出售掉之前的股票)
样例
给出一个样例数组 [4,4,6,1,1,4,2,5], 返回 6
注意
你不可以同时参与多笔交易(你必须在再次购买前出售掉之前的股票)
class Solution { /** * @param prices: Given an integer array * @return: Maximum profit */ public int maxProfit(int[] prices) { if(null == prices || prices.length < 2)return 0; int[] profitLeft = new int[prices.length]; int[] profitRight = new int[prices.length]; int minPrice = prices[0]; for(int i = 1; i < prices.length; i++) { profitLeft[i] = Math.max(profitLeft[i - 1], prices[i] - minPrice); minPrice = Math.min(minPrice, prices[i]); } int maxPrice = prices[prices.length - 1]; for(int i = prices.length - 2; i >= 0; i--) { profitRight[i] = Math.max(profitRight[i + 1], maxPrice - prices[i]); maxPrice = Math.max(maxPrice, prices[i]); } int result = 0; for(int i = 0; i < prices.length; i++) { result = Math.max(result, profitLeft[i] + profitRight[i]); } return result; } };
相关文章推荐
- RT5350 安装 读卡器驱动
- 数据结构——树的简单操作集合
- Matlab--随机变量的数字特征
- ACM寻找连续的数的乘积最大值
- 企业支付宝账号开发接口教程--JAVA-UTF-8(实际操作完善中...SpringMVC+JSP)
- CSS 伪类/元素
- 如何调试报表插件
- RHEL十六(使用VIM编辑器)
- Linux命令详解 -- alias
- HDU 5316 Magician(2015多校第三场 线段树)
- 安卓欢迎页和phonegap安卓欢迎页制作
- HDU 5323(2015多校3)-Solve this interesting problem(dfs+剪枝)
- HDOJ-2120 Ice_cream's world I(包含中文题意)
- [LeetCode] 038. Count and Say (Easy) (C++/Python)
- 计算性质
- RHEL十五(通过GREP使用正则表达式)
- 基于CLM(Constrained local model)人脸点检测算法
- GTK进阶学习:定时器
- InvalidateRect(rect) 防止图片移动时发生闪烁
- mysql的数据类型int、bigint、smallint 和 tinyint取值范围