LeetCode-探索-初級算法-動態規劃-2. 買賣股票的最佳時機(個人做題記錄,不是習題講解)
LeetCode探索-初級算法:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/
- 買賣股票的最佳時機
-
語言:java
-
思路:和之前數組的買賣股票題目那個有點像,不過這個是隻能進行一次交易。那麼也求每個之間的差值,尋找一個差值相加後 > 0的最大值,就是最大利潤。
-
代碼(1ms):
class Solution { public int maxProfit(int[] prices) { int sum = 0; int max = 0; int diff = 0; for(int i = 1; i < prices.length; ++i){ diff = prices[i] - prices[i-1]; if(sum + diff > 0) sum += diff; else sum = 0; max = max > sum ? max : sum; } return max; } }
-
參考代碼(0ms):即遍歷一次,遍歷中,要是min比當前小,則考慮更換最小值;反之,比min大,則考慮當前與min的插值是不是所需的最大利潤
class Solution { public int maxProfit(int[] prices) { int max = 0; int min = Integer.MAX_VALUE; for (int price : prices) { if (min > price) { min = price; } else if (price - min > max) { max = price - min; } } return max; } }
-
參考後重寫(1ms):慢了估計涉及優化問題。暫不考慮。
class Solution { public int maxProfit(int[] prices) { int max = 0; int min = Integer.MAX_VALUE; for(int i = 0; i < prices.length; ++i){ if(min > prices[i]){ min = prices[i]; }else{ int tmp = prices[i] - min; if(tmp > max) max = tmp; } } return max; } }