leetCode练习(123)
来源:互联网 发布:回到未来知乎 编辑:程序博客网 时间:2024/05/10 00:09
题目:Best Time to Buy and Sell Stock III
难度:hard
问题描述:
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 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).
解题思路:121题的拓展,121题只需要交易一次,顺序遍历一遍即可找到最大差。现在可以交易两次,我们容易想到,只要计算出所有prices[0,i]和prices[I,len-1]的和,找到最大的即可。对于prices[0,i] 同121题,只需遍历一次储存到firstProfit[]中即可。对于prices[I,len-1],我们可以从后往前遍历一遍即可。储存在secondProfit[]中,最后找到i使得firstProfit[I]+SecondProfit[I]最大就是最大贸易值。
代码如下:
public static int solution(int[] prices){if(prices==null||prices.length<2) return 0;int len=prices.length;int[]firstProfit=new int[len];int[]secondProfit=new int[len];int min=prices[0];for(int i=1;i<len;i++){min=Math.min(min, prices[i]);firstProfit[i]=Math.max(firstProfit[i-1], prices[i]-min);}int max=prices[len-1];for(int i=len-2;i>=0;i--){max=Math.max(max, prices[i]);secondProfit[i]=Math.max(secondProfit[i+1], max-prices[i]);}int res=0;for(int i=0;i<len;i++){res=Math.max(res, firstProfit[i]+secondProfit[i]);}return res;}
0 0
- leetCode练习(123)
- leetCode练习(7)
- leetCode练习(9)
- leetCode练习(2)
- leetCode练习(14)
- leetCode练习(3)
- leetCode练习(4)
- leetCode练习(19)
- leetCode练习(18)
- leetCode练习(5)
- leetCode练习(15)
- leetCode练习(20)
- leetCode练习(21)
- leetCode练习(16)
- leetCode练习(17)
- leetCode练习(11)
- leetCode练习(24)
- leetCode练习(22)
- ios开发——使用CALayer和Core Animation做动画效果
- C++IO流:你不知道的事(二)
- 洛谷2296 寻找道路
- Unity手游之路<十三>手游代码更新策略探讨
- C专家编程 六 typedef
- leetCode练习(123)
- 6.0删除了apache http client 联网方式
- JAVA中 就字母由 A=>Z 递增 和 Z=>A 递减的输出问题
- js验证数据格式和文本框是否为空
- 宽放大模式——一种前端模块化的方式探讨
- OpenCV之仿射变换:平移、缩放、旋转
- Android app瘦身计划
- 洛谷1073 最优贸易
- linux input 子系统分析