Best Time to Buy and Sell Stock

Updated on 12 May, 2025
Best Time to Buy and Sell Stock header image

Problem Statement

In this scenario, you are provided with an array called prices, where each element prices[i] represents the stock price on day i. The challenge is to determine the maximum profit possible by executing exactly one buy and one sell action. It's vital to note that the buying day must precede the selling day. The profit is defined as the difference between the selling price and the buying price. If there are no profitable transactions possible (i.e., no scenario where the selling price is greater than the buying price on a later day), the output should be 0. Your solution should efficiently compute the maximum profit achievable under these conditions.

Examples

Example 1

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.

Example 2

Input:

prices = [7,6,4,3,1]

Output:

0

Explanation:

In this case, no transactions are done and the max profit = 0.

Constraints

  • 1 <= prices.length <= 105
  • 0 <= prices[i] <= 104

Approach and Intuition

To solve this problem, you can use a simple yet effective approach that iterates through the list of prices while keeping track of two critical variables:

  1. The minimum price encountered so far (min_price).
  2. The maximum profit that could be achieved with the current price point (max_profit).

Here's a step-by-step breakdown of the approach:

  1. Initialize min_price with a very high value initially, and max_profit with 0.
  2. Traverse through each price in the array:
    • Update the min_price to be the smallest value between the current min_price and the current price.
    • Calculate the potential profit by subtracting the min_price from the current price.
    • Update the max_profit to be the maximum value between the current max_profit and the calculated potential profit.
  3. At the end of the loop, max_profit will hold the maximum profit possible without violating the rules of buying before selling.

Explanation using examples:

  • Example 1: For an input array [7,1,5,3,6,4], the maximum profit is achieved by buying at price 1 (Day 2) and selling at price 6 (Day 5), which yields a profit of 5.
  • Example 2: For an input array [7,6,4,3,1], prices only decrease, thus no profit can be made. The algorithm will correctly return a profit of 0, as it follows the progression of checking and updating min_price and max_profit.

The above approach works within the constraints given, efficiently dealing with both small and larger arrays up to a length of (10^5). This ensures that the solution will run within a reasonable time frame for all input sizes allowed by the constraints.

Solutions

  • C++
  • Java
  • C
  • JavaScript
  • Python
cpp
class Solution {
public:
    int calculateMaxProfit(vector<int>& stockPrices) {
        int lowestPrice = INT_MAX;
        int highestProfit = 0;
        for (int i = 0; i < stockPrices.size(); i++) {
            if (stockPrices[i] < lowestPrice)
                lowestPrice = stockPrices[i];
            else if (stockPrices[i] - lowestPrice > highestProfit)
                highestProfit = stockPrices[i] - lowestPrice;
        }
        return highestProfit;
    }
};

The provided C++ solution addresses the "Best Time to Buy and Sell Stock" problem by efficiently tracking the minimal stock price and calculating the maximum profit achievable. Working through an array of daily stock prices, the function calculateMaxProfit leverages a loop to inspect every price:

  • Initializes lowestPrice to INT_MAX to ensure any stock price will be considered lower initially.
  • Initializes highestProfit to 0, representing no profit scenario as the baseline.
  • Iterates through the list of stock prices, updating the lowestPrice if a current price is lower than any previously recorded prices.
  • Checks for potential profit by subtracting the lowestPrice from the current price. If this profit surpasses highestProfit, it updates highestProfit accordingly.

This method guarantees that you capture the maximum possible profit from single buy and sell transactions without needing a nested loop, thereby operating in linear time complexity, O(n). The solution is both time-efficient and easy to understand, making optimal use of resources.

java
public class Solution {
    public int calculateMaxProfit(int[] stockPrices) {
        int lowestPrice = Integer.MAX_VALUE;
        int highestProfit = 0;
        for (int i = 0; i < stockPrices.length; i++) {
            if (stockPrices[i] < lowestPrice) lowestPrice = stockPrices[i];
            else if (stockPrices[i] - lowestPrice > highestProfit) highestProfit = stockPrices[i] - lowestPrice;
        }
        return highestProfit;
    }
}

This solution summary describes an approach to solving the "Best Time to Buy and Sell Stock" problem using Java, focusing on maximizing profit given the price of a stock over several days.

  • The solution is implemented within a class named Solution with a method called calculateMaxProfit.
  • It accepts an integer array stockPrices which represents the stock price on each day.

The method functions as follows:

  • Initialize lowestPrice to Integer.MAX_VALUE. This variable will hold the minimum price of the stock observed so far.
  • Initialize highestProfit to 0. This variable will keep track of the maximum profit achieved at any given point.
  • Use a single loop to iterate through the array stockPrices.
    • For each price in the array:
      • Update lowestPrice to the current price if the current price is lower than lowestPrice.
      • If the current price is higher than lowestPrice, calculate the potential profit (stockPrices[i] - lowestPrice).
      • If this potential profit exceeds highestProfit, update highestProfit with this new value.
  • The method returns highestProfit, which will be the maximum achievable profit by buying low and selling high at optimal times.

This solution efficiently calculates the maximum possible profit with a time complexity of O(n), where n is the number of days, and requires O(1) additional space. The method ensures that the buying and selling happen in the right order (you cannot sell the stock before you buy it). This approach effectively captures the best trading scenario by maintaining the lowest prices seen so far and the highest possible profit at any stage.

c
int calculateMaxProfit(int* stockPrices, int numberOfDays) {
    int lowestPrice = INT_MAX;
    int highestProfit = 0;
    for (int day = 0; day < numberOfDays; day++) {
        if (stockPrices[day] < lowestPrice)
            lowestPrice = stockPrices[day];
        else if (stockPrices[day] - lowestPrice > highestProfit)
            highestProfit = stockPrices[day] - lowestPrice;
    }
    return highestProfit;
}

This solution is implemented in C to solve the problem of determining the best time to buy and sell stock for maximum profit. The function, calculateMaxProfit, takes an array of stock prices and the number of days as its parameters.

Follow these steps to understand how the code works:

  1. Initiate lowestPrice with INT_MAX to ensure any price in the array is lower initially.
  2. Set highestProfit to zero, this will store the maximum profit found.

The function then enters a loop iterating over each day:

  1. If the current day's stock price is lower than the lowestPrice, update lowestPrice to this value.
  2. If the difference between the current day's stock price and lowestPrice is greater than highestProfit, update highestProfit accordingly.

Finally, the function returns the highestProfit which represents the maximum profit that could be achieved based on the given stock prices and number of days.

This approach ensures checking each possible day's profit in relation to the lowest price seen so far, leading to an efficient solution with a time complexity of O(n), where n is the number of days. This method is particularly effective for large arrays, providing a quick way to determine the best buy and sell points without the need for nested loops or additional data structures.

js
var getMaximumProfit = function (priceList) {
    let lowestPrice = Number.MAX_VALUE;
    let highestProfit = 0;
    for (let index = 0; index < priceList.length; index++) {
        if (priceList[index] < lowestPrice) lowestPrice = priceList[index];
        else if (priceList[index] - lowestPrice > highestProfit)
            highestProfit = priceList[index] - lowestPrice;
    }
    return highestProfit;
};

The solution presented above is designed to find the maximum profit from a list of stock prices using JavaScript. The function getMaximumProfit takes an array priceList as input, where each element represents the stock price on a given day.

Follow these principles to understand how the function operates:

  • Initialize lowestPrice to the maximum possible value that a number in JavaScript can hold. This helps in ensuring any price in the list is lower than this initial value.
  • Set highestProfit to 0 as a starting point.
  • Iterate through each price in the priceList array:
    • If the current price is less than lowestPrice, update lowestPrice to this current price.
    • If the current price minus lowestPrice is greater than highestProfit, update highestProfit to this difference.
  • After iterating through all prices, highestProfit will hold the maximum possible profit.

This efficient approach ensures that the function processes each price in the list only once, thus having a linear time complexity of O(n), where n is the number of days (or stock prices) in the input list. The simplicity of using a single loop and conditional checks makes the code straightforward and efficient for large inputs.

python
class Solution:
    def calculateMaxProfit(self, costs: List[int]) -> int:
        lowest_price = float("inf")
        highest_profit = 0
        for price in costs:
            if price < lowest_price:
                lowest_price = price
            elif price - lowest_price > highest_profit:
                highest_profit = price - lowest_price

        return highest_profit

The provided solution in Python addresses the problem of determining the best time to buy and sell stock to maximize profit. Implement the following logic:

  1. Declare two variables: lowest_price initialized to infinity to keep track of the minimum stock price encountered so far, and highest_profit initialized to zero for tracking the maximum profit possible.
  2. Iterate over the list of stock prices:
    • When a stock price less than the lowest_price is encountered, update lowest_price.
    • If the current price minus lowest_price yields a profit greater than highest_profit, update highest_profit with this new profit value.
  3. Return the highest_profit, which will be the maximum profit from selling and buying on optimal days.

This method ensures efficiency by computing the result in a single pass through the stock prices, giving a time complexity of O(n). It effectively finds the lowest buy price and the highest profit without needing a nested loop, thus optimizing performance.

Comments

No comments yet.