Best Time to Buy and Sell Stock

The Solution to LeetCode easy problem

Sukanya Bharati
TheLeanProgrammer
3 min readOct 19, 2021

--

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.

Example 1:

Example 2:

Constraints:

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

I will share two approaches here to solve the above problem-one is the Brute Force Approach & the Optimized Approach.

Brute Force Approach

In this for every element traverse the rest part of the array and find the profit using prices[j]-prices[i]; and keep comparing to find the maximum profit.

Since for every element you will have to traverse the rest part of the array, the time complexity will be O(n*n), but the space complexity will remain as O(1).

PS: I have given the logic above, try to code it yourself.💻✔

Optimal Approach

In this approach, we will do a linear traversal, our approach would be to find the smallest element in the left half and find the largest element in the other half. Simultaneously I will keep comparing to find the maximum profit.

Now let us do a dry run of the solution to understand it better.

Time Complexity — O(n)

Space Complexity -O(1)

I am sharing some useful resources below :

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

https://www.youtube.com/watch?v=eMSfBgbiEjk&list=PLgUwDviBIf0rPG3Ictpu74YWBQ1CaBkm2&index=12

Hope you have understood the approach above. In case of any queries feel free to comment below. Till then keep coding and keep learning, Remember consistency is the key!!!

Since you enjoyed reading my blog , why not buy me a coffee and supoort my work here!! https://www.buymeacoffee.com/sukanyabharati

Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter tinyletter.com/TheLeanProgrammer

--

--

Sukanya Bharati
TheLeanProgrammer

A happy , motivated & a curious soul if you end up finding me 😎😁.