Leetcode Best Time to Buy and Sell Stock III
来源:互联网 发布:高通编译linux 编辑:程序博客网 时间:2024/06/09 01:15
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).
Difficulty: Hard
Solution: DP
public class Solution { public int maxProfit(int[] prices) { int len = prices.length; if(len == 0) return 0; if(len == 1) return 0; int[] nodes = new int[len]; int[] nodes_re = new int[len]; int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; for(int i = len - 1; i >= 0; i--){ max = Math.max(max, prices[i]); if(i < len - 1) nodes_re[i] = Math.max(nodes_re[i + 1], max - prices[i]); } for(int j = 0; j < len; j++){ min = Math.min(min, prices[j]); if(j > 0) nodes[j] = Math.max(nodes[j - 1], prices[j] - min); } int ans = 0; for(int i = 0; i < len - 1; i++){ ans = Math.max(ans, nodes[i] + nodes_re[i + 1]); } return Math.max(ans, nodes[len - 1]); }}
0 0
- 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
- LeetCode-Best Time to Buy and Sell Stock III
- MAC Android Eclipse开发环境设置
- java中的时间转化问题
- Codeforces Round #361 (Div. 2)
- Scala插入排序
- ios开发网络请求出现:App Transport Security has blocked a cleartext HTTP (Xcode 7.3.1关键字有所变化)
- Leetcode Best Time to Buy and Sell Stock III
- 处理html页面的空格问题(DOM)
- Linux下的库操作工具-nm、ar、ldd、ldconfig和ld.so
- absent line number information
- 使用ufsdump/ufsrestore和tar迁移ufs文件系统
- 微信图片另存失败?这得从SNI说起
- tight word
- 13_04_Linux进程管理之二
- POJ-1144 Network((割顶)