LeetCode--121. Best Time to Buy and Sell Stock && 122. Best Time to Buy and Sell Stock II
阿新 • • 發佈:2019-01-01
連續AC了5條medium有點疲憊,休息一下來兩條easy放鬆放鬆。
題目連結:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/和https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
題目一要求找到股票最佳的買入賣出時間(最大化利潤)
思路一:暴力計算每種可能性
class Solution { public int maxProfit(int[] prices) { int max=0; for(int i=0;i<prices.length-1;i++) for(int j=i+1;j<prices.length;j++) max=Math.max(max,prices[j]-prices[i]); return max; } }
思路二:維護一個最小股價和最大利潤的變數
class Solution { public int maxProfit(int[] prices) { int minPrice=Integer.MAX_VALUE; int maxProfit=0; for(int i=0;i<prices.length;i++) { minPrice=Math.min(minPrice,prices[i]); maxProfit=Math.max(maxProfit,prices[i]-minPrice); } return maxProfit; } }
題目二要求多次買入賣出的最大收益,實際上是在求所有股票增長階段收益的綜合,使用雙指標來解決就可,程式碼也比較簡單,注意邊界條件的判斷即可:
class Solution { public int maxProfit(int[] prices) { int maxProfit=0; int i=0,j=0; while(j<prices.length-1) { while(j<prices.length-1 && prices[j+1]>prices[j]) j++; if(j!=i) maxProfit += prices[j]-prices[i]; i=j+1; j=i; } return maxProfit; } }