DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on

Best time to Buy and Sell Stock

I am going to start posting about Blind 75 LeetCode Questions.

Today I will be solving the Best time to Buy and Sell Stock Problem

Let`s set up the problem first.

We are being asked to return the maximum profit you can achieve from the transaction and if we cannot achieve any profit, we should return 0.

We will need to start defining two variables

Image description

The first variable is where we will store the final value, the second variable is to store the first price value.

Now we will see how will be the for loop we are going to use.
Image description

On the first line we will start the for loop where we will define the "sell" variable with one, then we will make it to go over it just when "sell" it is less than the price length and finally summing 1 for every loop.

The next line there is a variable where we are storing the value "prices[sell]" where sell is the loop to every value.

The next line we are creating a variable called "profit" where we are doing a subtraction between "sellPrice" and "minPrice".

The next line we are re defined "maxProfit" in order to get the max profit with the "Math.max" function.

The next line we are making an if statement checking if "sellPrice" is smaller than "minPrice" and if this statement is true we will define "minPrice" equal to "sellPrice".

I will leave the hole code here.

Image description

Thanks, i will be uploading every day.
Hope someone found it useful.

Lautaro.

Top comments (0)