121. 122.123 Best Time to Buy and Sell Stock
来源:互联网 发布:微信点菜系统源码 编辑:程序博客网 时间:2024/06/06 09:29
Best Time to Buy and Sell Stock
Example 1:
Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]Output: 0In this case, no transaction is done, i.e. max profit = 0.
1. 找出最大和最小
2. 如果prices[I] < min 对调
if(prices.length == 0) return 0;int min = prices[0];int max = 0;for (int i = 1; i < prices.length; i++) {if(prices[i] < min) min = prices[i];else if(prices[i] - min > max) {max = prices[i] - min;}}return max;
121. Best Time to Buy and Sell StockII
1. 不限交易次数,只要可以赚就交易if(prices.length == 0) return 0; int max = 0; for(int i = 1; i < prices.length; i++) { if(prices[i] > prices[i - 1]) { max += prices[i] - prices[i - 1]; } } return max;
123. Best Time to Buy and Sell Stock III
限制在两次交易内
1. 先计算出子序列[0,...,i]中的最大利润,用一个数组保存下来,那么时间是O(n)。
2. 逆向扫描,计算子序列[i,...,n-1]上的最大利润,这一步同时就能结合上一步的结果计算最终的最大利润了,这一步也是O(n)。
public int maxProfit(int[] prices) { if(prices.length == 0) return 0; int max = 0; //前0 - i个 int[] one = new int[prices.length]; one[0] = 0; int min = prices[0]; for(int i = 1; i < prices.length; i++) { if(prices[i] < min) min = prices[i]; else if(prices[i] - min > max) max = prices[i] - min; one[i] = max; } //后 i - n-1 逆向遍历 int[] two = new int[prices.length]; two[prices.length - 1] = 0; max = 0; int high = prices[prices.length - 1]; for(int i = prices.length - 2; i >= 0; i--) { if(prices[i] > high) high = prices[i]; else if(high - prices[i] > max) max = high - prices[i]; two[i] = max; } //再进行划分,分别计算两个部分 for(int i =0; i < prices.length; i++) { int ret = one[i] + two[i]; if(max < ret) max = ret; } return max; }
0 0
- 121. 122.123 Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time To Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- 关于Java Unsafe
- C#入门 自用笔记 9*9算术表的生成。
- 机器学习(周志华 )-2模型评估与选择
- RDC 表达式
- 关于ajax的学习笔记(心得)
- 121. 122.123 Best Time to Buy and Sell Stock
- LDS文件格式分析
- 德国CeBIT 2017,数字冰雹开启智慧城市决策新视角
- 淘淘商城第二天
- SQL数据类型、基本表的定义、索引定义
- 高并发相关
- Android tv 获取第三方icon的颜色,并填充该背景
- 几个不错的Android开源音视频播放器
- artTemplate if else 简洁语法