Best Time to Buy and Sell Stock
Description
You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to
maximize your profit by choosing a single day to buy one stock and choosing a different day in the
future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot
achieve any profit, return 0.
Sample Test Case
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.
Solution Approach
We track the minimum price encountered so far and calculate potential profit at each day. The
maximum profit is updated accordingly.
Solution Code
class Solution:
def maxProfit(self, prices):
min_price = float('inf')
max_profit = 0
for price in prices:
if price < min_price:
min_price = price
elif price - min_price > max_profit:
max_profit = price - min_price
return max_profit
Time Complexity
Time Complexity: O(n), Space Complexity: O(1)