DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on

1

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.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay