leetCode 123. Best Time to Buy and Sell Stock III
来源:互联网 发布:form表单转json 编辑:程序博客网 时间:2024/05/14 02:31
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).
给一个一维数组,代表每天股票价格,找出交易两次最大的获利选择
例如
Input: [7, 1, 5, 3, 6, 4]
最大为7,即【1,5】=4,【3,6】=3
用dp1[i]记录maxprofit[0,i],
用dp2[i]记录maxprofit[i,len-1]
输出就是max(dp1[i]+dp2[i]), i=0~n-1
public static int maxProfit(int[] prices) { int len = prices.length; if(len<=1)return 0; int max=0; int dp1[] = new int[len]; int curmin= prices[0]; for(int i=1;i<len;i++){ max = max < prices[i] - curmin ? prices[i] - curmin : max; curmin = prices[i] < curmin ? prices[i] : curmin; dp1[i] = max; } int curmax= prices[len-1]; max=0; int dp2[] = new int[len]; for(int i=len-1;i>=0;i--){ max = max < curmax-prices[i] ? curmax-prices[i] : max; curmax = prices[i] > curmax ? prices[i] : curmax; dp2[i] = max; } max=0; for(int i=len-1;i>0;i--){ max = max < dp1[i]+dp2[i] ? dp1[i]+dp2[i] : max; } return max; }
阅读全文
0 0
- LeetCode 123. Best Time to Buy and Sell Stock III
- [Leetcode]123.Best Time to Buy and Sell Stock III
- [Leetcode] 123. Best Time to Buy and Sell Stock III
- [leetcode] 123.Best Time to Buy and Sell Stock III
- 【leetcode】123. Best Time to Buy and Sell Stock III
- [leetcode] 123. Best Time to Buy and Sell Stock III
- leetcode 123. Best Time to Buy and Sell Stock III
- leetcode 123. Best Time to Buy and Sell Stock III
- [LeetCode] 123. Best Time to Buy and Sell Stock III
- Leetcode 123. Best Time to Buy and Sell Stock III
- 【leetcode】123. Best Time to Buy and Sell Stock III
- LeetCode 123. Best Time to Buy and Sell Stock III
- leetcode-123. Best Time to Buy and Sell Stock III
- [LeetCode]123. Best Time to Buy and Sell Stock III
- LeetCode 123. Best Time to Buy and Sell Stock III
- [leetcode]123. Best Time to Buy and Sell Stock III
- [Leetcode] 123. Best Time to Buy and Sell Stock III
- [LeetCode]123. Best Time to Buy and Sell Stock III
- "红砖"JS高程笔记P1
- vue资料合集
- 解决warning: Ignoring InnerClasses attribute for an anonymous inner class
- jps后发现namenode 没有启动
- http://blog.csdn.net/lonsegdi/article/details/46333425
- leetCode 123. Best Time to Buy and Sell Stock III
- linux命令
- (总结)Oracle 11g常用管理命令(用户、表空间、权限)
- PD4ML Cookbook PDF and True Type fonts(2)
- 微信小程序将图片数据流添加到image标签中
- JavaWeb中读取文件资源的路径问题
- [POJ 1715] Hexadecimal Numbers 求排列数/数位DP
- referrer属性(获取本页的URL,上一页URL)
- 文章标题