Best Time to Buy and Sell Stock

Buying and Selling Stocks Problem – Hard Level Problem

You are given an array prices, where each element prices[i] represents the price of PrepCoin on the i-th day.

Your task is to determine the maximum profit you can make by selecting one day to buy a PrepCoin and another day after it to sell.

If it’s not possible to make any profit (e.g., prices are decreasing every day), you should return 0. This means you can also choose not to make any transactions.

Buy and Sell Stock at right time

Explanation : Buy prices[1] and sell prices[4], profit = 7 – 1 = 6.

Explanation : No profitable transactions can be made, thus the max profit is 0.

Constraints:

  • 1 <= prices.length <= 100
  • 0 <= prices[i] <= 100

Buying and Selling Stocks Solution

Recommendation for Time and Space Complexity –You should aim for a solution with O(n) time and O(1) space, where n is the size of the input array.

Hints for solving problems

Hint 1 :

A brute force approach involves iterating through the array with index i, treating it as the buying day, and checking all possible selling options on the days after i. This results in a time complexity of O(n²). Can you think of a more efficient solution?

Hint 2 :

You should buy at a price and always sell at a higher price. Can you iterate through the array with index i, considering it as either the buying price or the selling price?

There are mainly 3 approach to solve this problem-

  1. Brute Force Method
  2. Two Pointers Method
  3. Dynamic Programming Method

1. Brute Force Method

This method check all possible pairs of days to calculate the maximum profit by iterating through every possible buy and sell combination. This approach has a time complexity of O(n^2).

  • Time complexity: O(n^2)
  • Space complexity: O(1)

Code

2. Two Pointers Method

Use a single pass with two variables to track the minimum price so far and the maximum profit, updating them as you traverse the array. This has a time complexity of O(n).

  • Time complexity: O(n)
  • Space complexity: O(1)

Code

3. Dynamic Programming Method

This method maintain a table or array to store intermediate results, such as the minimum price up to a given day and the maximum profit calculated so far, optimizing computation over multiple traversals. Time complexity is O(n).

  • Time complexity: O(n)
  • Space complexity: O(1)

Code

More Articles