150強訪談簡單

買賣股票的最佳時機

「買賣股票的最佳時機」問題的詳細指南和 Python 實施。

問題陳述

簡單

給您一個陣列 prices,其中 prices[i] 是給定股票在第 i 天的價格。

您希望透過選擇某一天購買一隻股票並選擇未來的另一天出售該股票來最大化您的利潤。

返回您可以從本次交易中獲得的最大利潤。如果您無法獲得任何利潤,請返回 0

寫一個函數 maxProfit(prices: List[int]) -> int

約束條件
  • 1 <= len(prices) <= 10^5
  • 0 <= prices[i] <= 10^4

範例

Example 1
Input
prices = [7, 1, 5, 3, 6, 4]
Output
5
Explanation

Buy on day 2 (price = 1) and sell on day 5 (price = 6). Profit = 6 - 1 = 5.

Example 2
Input
prices = [7, 6, 4, 3, 1]
Output
0
Explanation

No profitable transaction is possible since prices only decrease.

Need a Hint?
考慮使用滑動視窗特定的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。