Leetcode123 hard
来源:互联网 发布:我要复仇知乎 编辑:程序博客网 时间:2024/06/09 23:29
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.
解析:很容易想出将原有数组分为两个部分,分别找出左半部分和右半部分最大的利润值。从第二个位置开始分,然后将两边利润值相加找到两次买入和卖出的最大利润,这里的技巧就是使用两个数组分别记录以某个位置分隔,左半部分和右半部分的最大利润值。求解利润值关键在于如何求得某一段数组的最大利润,并是在O(n)复杂度内完成。在扫描时,我们希望买入值尽量的小,卖出值尽量的大,所以当某个位置的加个小于买入价格时,需要更新买入价格。同时利润值为当前的价格减掉最小的买入价格,最后找出最大利润即可。由于是顺序扫描,不会出现卖出是在买入之前。同理我们可以逆着数组扫描,但是注意逆着扫描就一定要记录最大卖出值。然后同理找出最大利润。
以下附已AC的JAVA源代码:
// 123hpublic int maxProfit123(int[] prices) {if (prices == null || prices.length < 2) {return 0;}if (prices.length == 2) {if (prices[1] > prices[0]) {return prices[1] - prices[0];}return 0;}int prL[] = new int[prices.length];int prR[] = new int[prices.length];int bugMin = prices[0];int proMax = 0;for (int i = 0; i < prices.length; i++) {int pro = prices[i] - bugMin;proMax = pro > proMax ? pro : proMax;if (prices[i] < bugMin) {bugMin = prices[i];}prL[i] = proMax;}int sellMax = prices[prices.length - 1];proMax = 0;for (int i = prices.length - 1; i >= 0; i--) {int pro = sellMax - prices[i];proMax = pro > proMax ? pro : proMax;if (prices[i] > sellMax) {sellMax = prices[i];}prR[i] = proMax;}proMax = 0;for (int mid = 1; mid < prices.length - 1; mid++) {int pro = prL[mid] + prR[mid];proMax = pro > proMax ? pro : proMax;}return proMax;}
0 0
- Leetcode123 hard
- hard
- Leetcode123: Letter Combinations of a Phone Number
- leetcode123---Best Time to Buy and Sell Stock III
- LeetCode123:Best Time to Buy and Sell Stock III
- leetcode123 Best Time to Buy and Sell Stock III
- LeetCode123. Best Time to Buy and Sell Stock III
- leetcode123. [DP]Best Time to Buy and Sell Stock III
- LeetCode123—Best Time to Buy and Sell Stock III
- LeetCode123 Best Time to Buy and Sell Stock III
- Leetcode123. Best Time to Buy and Sell Stock III
- hard code & hard working & hard night
- Tips_IC(hard)
- Hard Drive
- hard work
- Hard Road
- hard limits
- hard work
- android编译系统分析(二)mm编译单个模块
- HDOJ 5326 Work(类似并查集)
- java8中的系统时间获取
- 独木桥
- Ubuntu Server如何配置SFTP
- Leetcode123 hard
- Rxjava(变换类)-Window
- nginx入门(1)
- Android 手机开发和机顶盒开发的区别(软件角度)
- BSOJ1054 洛谷P1054 CODEVS1107【NOIP 2005提高】等价表达式 随机化
- android编译系统分析(三)make
- MyBatis学习总结(八)——Mybatis3.x与Spring4.x整合
- JAVA.SECURITY.POLICY 配置说明
- mac OSX 创建nginx + rtmp本地推流服务器