Best Time to Buy and Sell Stock — Day 21(Python)

Image for post
Image for post
Photo by Markus Winkler on Unsplash

Today’s question is another easy tagged question from leetcode. Let us jump into the problem without wasting much time.

121. Best Time to Buy and Sell Stock

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Example 2:

One way to solve the given problem is by finding the profits by considering all buy and sell options. How do we do that?

Consider the first number as a buy option. Consider all numbers after buy as sell options.
Find the difference between sell value and buy value. The profit earned would be a positive number. If we get no positive number, return 0.
The max among the profit earned is our result.

Complexity analysis

Time Complexity

We have two for loops which traverse through the entire list of prices twice. Hence the time complexity is O(N²), where N is the length of prices list.

Space Complexity

We are not using any extra space while implementing the algorithm, and hence the space complexity is O(1).

How should we improve the time complexity?

Can we try to implement the solution using one pass?

Initialize buy value as infinity, and profit earned as 0.

Traverse through each value, check if the current value is less than buy. If yes, the current number will be the buy value.

If no, check if the difference between the current value and buy value is higher than the profit. If yes, the difference between the current number and buy value is our profit.

Complexity analysis

Time Complexity

We have one for loops which traverse through the entire list of prices. Hence the time complexity is O(N), where N is the length of prices list.

Space Complexity

We are not using any extra space while implementing the algorithm, and hence the space complexity is O(1).

I would love to hear your feedback about my posts. Do let me know if you have any comments or feedback.

Software Engineer. Find me @ www.linkedin.com/in/annamariya-jt

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store