algoadvance

Leetcode 121. Best Time to Buy and Sell Stock

Problem Statement

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.

Clarifying Questions

  1. Can prices contain negative numbers?
    • No, stock prices are always non-negative.
  2. What should be returned if the prices array is empty?
    • If the prices array is empty, the maximum profit should be 0.
  3. Is there any limitation to the size of the prices array?
    • Usually, the constraints are such that the solution should be efficient for reasonably large arrays (e.g., up to (10^5)).

Strategy

The goal is to find the maximum difference between a future selling price and a past buying price. We can achieve this by maintaining a minimum price seen so far and checking the potential profit at each step.

Steps:

  1. Initialize a variable to keep track of the minimum price encountered so far.
  2. Iterate through the prices array.
  3. For each price, calculate the potential profit if the stock is sold at that price (current price - minimum price so far).
  4. Track the maximum profit seen.
  5. At each step, update the minimum price if the current price is lower than the minimum price seen.

Code

#include <vector>
#include <algorithm>
#include <iostream>

class Solution {
public:
    int maxProfit(std::vector<int>& prices) {
        if (prices.empty()) return 0; // handle the edge case of an empty array
        
        int minPrice = INT_MAX; // Initialize minPrice to a very high value
        int maxProfit = 0;      // Initialize maxProfit to zero
        
        for (int price : prices) {
            if (price < minPrice) {
                minPrice = price; // Update the minimum price
            } else if (price - minPrice > maxProfit) {
                maxProfit = price - minPrice; // Update the maximum profit
            }
        }
        
        return maxProfit;
    }
};

int main() {
    Solution sol;
    std::vector<int> prices = {7, 1, 5, 3, 6, 4};
    std::cout << "Max Profit: " << sol.maxProfit(prices) << std::endl; // Output: 5
    return 0;
}

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI