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

121. Best Time to Buy and Sell Stock Leetcode Solution

Best Time to Buy and Sell Stock Leetcode Problem :

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

jump game leetcode

Best Time to Buy and Sell Stock Leetcode Solution :

Constraints :

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4

Example 1:

  • Input: prices = [7,6,4,3,1]
  • Output: 0

Approach :

1)We make 2 extra arrays, left and right
2)We initialize the first element of left array as the first element of prices
3)We initialize the last element of right array as the last element of prices
4)To get the maximum Profit, we need minimum from left array and maximum from right array.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Code :

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

Best time to buy and Sell stock in Python

Best time to buy and Sell stock in Python

On this page, we will learn to create a Program to find Best time to buy and Sell stock in Python programing language.

Example:

  • Input: [70, 150, 230, 280, 10, 505, 665]
  • Output: We can make a maximum profit of 655 
  • Explanation: For the given set of stock prices we can make a maximum profit of 655 by buying the stock on day 4 & selling it on day 6
Best time to buy and sell stock in Python

Problem Statement

 The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days.

Rules

  1. We are allowed to buy and sell only once
  2. We can not sell before buying the stock

 If the given array of prices is sorted in decreasing order, then profit cannot be earned at all.

 For example, if the given array is [70, 150, 230, 280, 10, 505, 665], the maximum profit of 655 can be earned by buying on day 4, selling on day 6.

Algorithm

  • Initialize a variable to store profit (pro)
  • Iterate using a for loop between 0 to one less then length of input array
  • Run a nested for loop from range i+1 to length of array
  • If arr[j] – arr[i] is greater then pro then change the value of pro to arr[j] – arr[i]
  • After the loop ends pro stores the required answer

Python Code

Run
def profit(arr):
    pro = 0
    for i in range(len(arr) - 1):
        for j in range(i + 1, len(arr)):
            if arr[j] - arr[i] > pro:
                pro = arr[j] - arr[i]
    return pro


array = [70, 150, 230, 280, 10, 505, 665]
print("We can make maximum profit of", profit(array))

Output

We can make maximum profit of 655

For similar question click on given button.