Best Time to Buy and Sell Stock III
来源:互联网 发布:阿里云 腾讯云 aws对比 编辑:程序博客网 时间:2024/04/29 18:02
题意:
股票最多可以交易两次,并且一次只能购买一个股票,下次购买前必须先出手当前的股票。
思路:
将第1至N天分为1-k,k-N两部分,第一部分最大利益 + 第二部分最大利益 = 结果。
若直接两层循环,时间复杂度为O(n^2),看到这样做的代码也能过。
O(n)做法:使用left[i],right[i]分别记录前i天最小值,后i—N天最大值,计算(p[i] - left[i]) + (right[i] - p[i])并且取最大值即为所求。
public class Solution { public int maxProfit(int[] p) { if(p.length == 0)return 0; int r[] = new int[p.length]; int l[] = new int[p.length]; int lM[] = new int[p.length]; int rM[] = new int[p.length]; l[0] = p[0]; lM[0] = 0; for(int i=1;i<p.length;i++){ if(p[i] < l[i-1])l[i] = p[i]; else l[i] = l[i-1]; lM[i] = Math.max(p[i] - l[i], lM[i-1]); } r[p.length-1] = p[p.length-1]; rM[p.length-1] = 0; for(int i=p.length-2;i>=0;i--){ if(p[i] > r[i+1])r[i] = p[i]; else r[i] = r[i+1]; rM[i] = Math.max(r[i] - p[i], rM[i+1]); } int res = 0; for(int i=0;i<p.length;i++) res = Math.max(res, lM[i] + rM[i]); return res; }}
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
- Best Time to Buy and Sell Stock III
- 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
- Best Time to Buy and Sell Stock III
- 【leetcode】Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- LeetCode - Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- 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
- Swing编程方面步骤之三JFrame、JPanel、paint与paintComponent的区别
- POS机预授权的具体操作步骤
- adb命令 学习 查找 方法
- 话题情感混合模型(JST)
- Mac下MySql的卸载方法
- Best Time to Buy and Sell Stock III
- POS机预授权的具体操作步骤
- DIKENI(迪柯尼)初夏风情,快意乐享轻夏生活
- LINUX内存管理(段式页式管理)《转》
- 抛异常找程序执行流程
- popToViewController用法
- 基本查询
- Kd-Tree算法原理和开源实现代码
- Bootstrap DataTable自定义表格 设置某列不排序