algoadvance

You are given an array prices where prices[i] is the price of a given stock on the i-th 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.

Example:

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.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Constraints:

Clarifying Questions

  1. Q: Can we have prices with zero or negative values? A: Prices can be zero, but they will not be negative.
  2. Q: Is it guaranteed to have distinct prices every day? A: No, prices can repeat across different days.
  3. Q: Can I assume input array is always valid (not empty)? A: Yes, as per the constraints, the length of the prices array is at least 1.

Strategy

  1. Initialize Variables:
    • min_price: a variable to store the minimum price encountered so far, initialized to a high value (infinity).
    • max_profit: a variable to store the maximum profit observed so far, initialized to 0.
  2. Iterate Through Prices:
    • For each price, update the min_price if the current price is lower than min_price.
    • Calculate the current_profit as the difference between the current price and min_price.
    • Update max_profit if current_profit is greater than max_profit.
  3. Return Result:
    • After iterating through all the prices, max_profit will hold the highest profit possible.

Code

Here is the implementation of the described strategy:

def maxProfit(prices):
    min_price = float('inf')
    max_profit = 0
    
    for price in prices:
        if price < min_price:
            min_price = price
        current_profit = price - min_price
        if current_profit > max_profit:
            max_profit = current_profit
            
    return max_profit

Time Complexity

This solution efficiently finds the maximum profit in linear time while maintaining constant space usage.

Try our interview co-pilot at AlgoAdvance.com