【Leetcode解題】121. Best Time to Buy and Sell Stock
題目
- 題目連結
- 目標函式 :
maxProfit(prices)- Input :
prices: List[int] - Output :
int
- Input :
解題概念
- 題意 : 給予一陣列
prices,其中prices[i]代表股票第i天的價格 - 需要選其中一天來買進,另外一天來賣出,題目結果為本次交易的最大利潤
我的寫法
- 想法 : 使用 for 迴圈去瀏覽每個元素
- 如果要找出最大利潤值,首先要找出
prices的最小值作為買進點 - 如果發現
price[i] - buy > max_profit,則將該值設為max_profit
- 如果要找出最大利潤值,首先要找出
- 程式碼 :
1
2
3
4
5
6
7
8
9
10
11
12def maxProfit(self, prices):
buy = prices[0]
max_profit = 0
for price in prices:
if price < buy:
buy = price
if price - buy > max_profit:
max_profit = price - buy
return max_profit - 成效 :
- Time Complexity : $\color{DB4D6D}{O(n)}$
- Runtime: 821 ms (faster than 93.80%)
- Memory Usage: 22.5 MB (more than 86.85%)
解答 or 其他優秀寫法
- 想法 : 基本上與我的想法相同,只有有些寫法是改用 while 迴圈和雙重指標去執行 searching
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Robin's Tech Blog!


