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.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay