To solve this problem, we need to determine the maximum gain possible by buying and selling a stock exactly once from a given list of daily stock prices.
Approach
The key insight here is to track two values as we iterate through the list of prices:
- Minimum Price: The lowest price encountered so far. This helps us determine the best possible buy price up to the current day.
- Maximum Profit: The highest profit we can achieve by selling at the current day's price (calculated as the difference between the current price and the minimum price seen so far).
By iterating through the list once, we can efficiently compute the maximum gain with a time complexity of O(n), where n is the number of elements in the list. This approach ensures we only traverse the list once, making it optimal.
Solution Code
def max_gain(prices):
if len(prices) < 2:
return 0
min_price = prices[0]
max_profit = 0
for price in prices[1:]:
current_profit = price - min_price
if current_profit > max_profit:
max_profit = current_profit
if price < min_price:
min_price = price
return max_profit
Explanation
- Edge Case Handling: If the list of prices has fewer than 2 elements, we return 0 because we can't perform a buy and sell transaction.
- Initialization: We start by setting the minimum price to the first element of the list and the maximum profit to 0.
- Iteration: For each subsequent price in the list:
- Calculate the potential profit if we sell at the current price (current price minus the minimum price seen so far).
- Update the maximum profit if the current profit is higher than the previously recorded maximum.
- Update the minimum price if the current price is lower than the previously recorded minimum.
- Result: The maximum profit value after processing all prices is the answer.
This approach efficiently computes the maximum gain by leveraging a single pass through the list, ensuring optimal performance. The space complexity is O(1) since we only use a few variables to track the necessary values.


作者声明:本文包含人工智能生成内容。