LeetCode 123 -- Best Time to Buy and Sell Stock III
来源:互联网 发布:linux 搭建cdn 编辑:程序博客网 时间:2024/05/19 19:41
LeetCode 123 -- Best Time to Buy and Sell Stock III
Say you have an array for which the ith element is the price of a given stock on dayi.
Design an algorithm to find the maximum profit. You may complete at mosttwo transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
answer:限定两次交易,求两次交易最大的利润。继续运用动态规划。给定一个点,求该点之前的一次交易赚取的最大利润和该点之后赚取的最大的利润。所以两次一前一后遍历。
取最大值。
<span style="font-size:14px;">public class Solution { public int maxProfit(int[] prices) { if(prices.length == 0) return 0; int res = 0 ; int n = prices.length; //正向遍历,opt[i]为0到i区间最大的利润 int[] opt = new int[n]; opt[0] = 0; int low = prices[0]; int curAns = 0; for(int i = 1; i < n ; i++){ if(prices[i] < low) low = prices[i]; else if(curAns < (prices[i] - low)){ curAns = (prices[i] - low); } opt[i] = curAns; } //反向遍历,revopt[i]为i到n的最大profit; int[] revopt = new int [n]; revopt[n-1] = 0; int high = prices[n-1]; int curAns1 = 0; for(int i = (n-2); i >= 0; i--){ if(prices[i] > high) high = prices[i]; else if(curAns1 < (high - prices[i])){ curAns1 = (high - prices[i]); } revopt[i] = curAns1; } //正反结合 for(int i = 0; i < n; i++){ if(res < (opt[i] + revopt[i])){ res = (opt[i] + revopt[i]); } } return res; }}</span>
0 0
- LeetCode 123: Best Time to Buy and Sell Stock III
- LeetCode: Best Time to Buy and Sell Stock III [123]
- 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
- 123 Best Time to Buy and Sell Stock III [Leetcode]
- Best Time to Buy and Sell Stock III - LeetCode 123
- 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 Best Time to Buy and Sell Stock III 123
- [Leetcode 123] Best Time to Buy and Sell Stock III
- **Leetcode 123 Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- context 获取多个sharepreferences
- vs中的lib和dll分别是什么?
- android shape的使用
- 安卓‘进度条ProgressBar’中‘setIndeterminate()’方法的辨析
- cdh5安装 lzo
- LeetCode 123 -- Best Time to Buy and Sell Stock III
- maven环境搭建
- PAT|1113. Integer Set Partition
- C# 命令行分析器
- Hibernate中Criteria的完整用法
- 组合模式
- ASIHTTPRequest类库简介和使用说明
- 虚拟机FAQ
- 简单工厂模式 单例工厂模式 工厂方法模式 抽象工厂模式 原型模式