问题1比较简单, 使用一个pre变量,记录之前最小值就可以了
public int maxProfit(int[] prices) { if (prices == null || prices.length == 0) { return 0; } int max = 0; int minPre = prices[0]; for (int i = 1; i < prices.length; i++) { int price = prices[i]; if(price<minPre){ minPre = price; }else if(price-minPre>max){ max = price-minPre; } } return max; }
问题2细想,其实也比较简单,就是将所有递增的两个数的差加起来
public int maxProfit(int[] prices) { if (prices == null || prices.length == 0) { return 0; } int preMin = prices[0]; int sum = 0; for (int i = 1; i < prices.length; i++) { int price = prices[i]; if (price < preMin) { preMin = price; } else if (price > preMin) { sum += price - preMin; } preMin = prices[i]; } return sum; }
第三个问题,需要细想下,直观的想法,将数组一份为二,得到没有个子数组的最大值,这个算法是O(n2)的时间复杂度,不过;仔细思考,其实我们可以通过三次o(n)的遍历,得到所求。事先我们可以得到正向遍历,反向遍历,每个index上的最大利润值,最后一次遍历就可完成计算。
public int maxProfit(int[] prices) { if (prices == null || prices.length == 0) { return 0; } int[] maxLeft = new int[prices.length]; int preMin = prices[0]; for(int i=1; i<prices.length; i++){ int price = prices[i]; if(price<preMin){ preMin=price; maxLeft[i] =maxLeft[i-1]; }else if(price-preMin>maxLeft[i-1]) { maxLeft[i]=price - preMin; }else { maxLeft[i] =maxLeft[i-1]; } } int[] maxRight = new int[prices.length]; int preMax = prices[prices.length-1]; for(int i=prices.length-2; i>=0; i--){ int price = prices[i]; if(price>preMax){ preMax = price; maxRight[i] = maxRight[i+1]; }else if(preMax - price>maxRight[i+1]){ maxRight[i]=preMax - price; }else { maxRight[i] = maxRight[i+1]; } } int max =0; for(int i=1; i<prices.length; i++){ if(maxLeft[i]+maxRight[i]>max){ max = maxLeft[i]+maxRight[i]; } } return max; }
相关推荐
java java_leetcode题解之Best Time to Buy and Sell Stock III.java
javascript js_leetcode题解之123-best-time-to-buy-and-sell-stock-iii.js
python python_leetcode题解之123_Best_Time_to_Buy_and_Sell_Stock_III
java lru leetcode leetcode-java leetcode刷题笔记 已做题目列表 1.Two Sum 3.Longest Substring Without Repeating Characters 5.Longest Palindromic Substring 20.Valid Parentheses 26.Remove Duplicates from ...
股票收益leetcode LeetCode 股票问题 Best Time to Buy and Sell Stock (Easy) 一次交易,找最大收益 for i in prices: low = min(low, i) profit = max(profit, i-low) Best Time to Buy and Sell Stock II (Easy) ...
[Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [C++](./C++/bitwise-and-of-numbers-range.cpp) [Python](./Python/bitwise-and-of-numbers-range.py) | _O(1)_...
Leetcode的ac是什么意思 LeetCodeInJava List #98 Validate Binary Search Tree #100 Same Tree #104 Maximum Depth of Binary Tree #122 Best Time to Buy and Sell Stock II #136 Single Number #150 Evaluate ...
- Best Time to Buy and Sell Stock III:存在多日限制交易,最多两次交易。 - Best Time to Buy and Sell Stock IV:与前三者不同,可能需要多次买入和卖出。 - Best Time to Buy and Sell Stock with Cooldown...
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 示例1 输入: [3,3,5,0,0,3,1,4] 输出: 6 解释: 在第 4 天...