Best Time To Buy And Sell Stock

To solve this coding challenge, we need to determine the maximum profit that can be made by buying and subsequently selling a stock on different days. The key constraint here is that we must buy the stock on a day before we sell it.

Explanation

Given an array of prices where
prices[i]
denotes the stock price on the ith day, we need to identify the best possible day to buy and the best possible future day to sell to maximize profit. We will employ a strategy that keeps track of the minimum price we've encountered so far as we iterate through the list, updating this minimum price along the way. Simultaneously, we'll keep a record of the maximum profit achievable by comparing the profit from the current day and the stored maximum profit.
Here’s the step-by-step methodology to solve this problem:
  1. Initialization:
    • Start by checking if the prices array is empty. If it is, return 0 as there is no way to make a profit.
    • Initialize
      min_price
      with the first day's price.
    • Initialize
      max_profit
      to 0, as no transactions have been done yet.
  2. Iterate Through Prices:
    • For each price in the array, check if it is lower than the current
      min_price
      . If so, update
      min_price
      .
    • Calculate the potential profit by subtracting
      min_price
      from the current price.
    • Compare this potential profit to the current
      max_profit
      and update
      max_profit
      if the new profit is higher.
  3. Return the Results:
    • After iterating through all prices, return
      max_profit
      which holds the maximum profit achievable.

    Pseudocode with Comments

                                                
    // Define the function to calculate the maximum profit
    function maxProfit(prices):
    
    // Check if the prices array is empty, return 0 since no transactions are possible
    if prices is empty:
    return 0
    
    // Initialize minimum price to the first element in prices
    min_price = prices[0]
    
    // Initialize maximum profit to 0 since no transactions have occurred yet
    max_profit = 0
    
    // Iterate through each price in the list
    for each price in prices:
    
    // If the current price is less than the minimum price seen so far
    if price < min_price:
    // Update the minimum price to the current price
    min_price = price
    else:
    // Calculate potential profit by selling at the current price
    potential_profit = price - min_price
    
    // Update the maximum profit if the potential profit is higher
    if potential_profit > max_profit:
    max_profit = potential_profit
    
    // Return the maximum profit found
    return max_profit
    
                                            

    Detailed Steps in Pseudocode:

  4. Check if the
    prices
    array is empty. This is crucial because an empty array signifies no stock prices available to analyze, leading to a direct return of 0, indicating no possible profit.
  5. Initialize
    min_price
    to the first price in the array. This sets our baseline for the lowest price seen so far as we begin with the first day's price.
  6. Initialize
    max_profit
    to 0, depicting no profit has been made yet. This will be the variable storing the highest profit as we iterate through the prices.
  7. Begin a loop through each
    price
    in the
    prices
    array:
    • Inside the loop, if the current
      price
      is less than
      min_price
      , update
      min_price
      to this new lower price. This ensures we are always buying at the lowest price observed up to the current point.
    • Calculate
      potential_profit
      as the difference between the current
      price
      and
      min_price
      . This represents the profit if we were to sell at the current day and had bought at the lowest price seen till now.
    • Compare
      potential_profit
      to
      max_profit
      and update
      max_profit
      if the
      potential_profit
      is greater. This ensures that we are capturing the best possible profit scenario.
  8. After completing the loop, return
    max_profit
    , which now holds the highest profit possible from the given price sequence.
Using this approach ensures a time complexity of O(n), where n is the length of the prices array, because we only pass through the list once. This efficiency is crucial given the constraints provided.