Best Time to Buy and Sell Stocks

Here we go again with another algorithm problem. This problem is called “Best time to Buy and Sell Stocks”.

This problem is giving you an array and tells you to treat the array like a timeline, for stock prices. In the array you are supposed to find the time to buy and sell that will give you the most profit, if you can not receive any profit the function should just return 0. So I would need to find a point in the array where it is the lowest and find the point where it rises to give the biggest profit, and if not return 0.

When planning out the problem I knew that the problem would require at least 2 variables, one to keep track of the profit and one to keep track of the day to buy the stocks. When I started out planning to solve the problem I was thinking about doing a loop within a loop. something that looks like the above example. However this example was inefficient and when looking at Big O Notation this example would be O(n²) this is bad because there are a bunch of unnecessary actions that are being executed which causes the function to take more memory and time to execute, as the problem gets bigger it will take up even more memory. So i had to find a better way to solve the problem.

In order to amend this problem I got rid of the loop in the loop there for making it be O(n) which is a lot better. In this function we go through the loop and there is an if statement that would is looking for the smallest value in the array, and there is another if statement that looks for the biggest profit, or difference between the first day of investment and the best day to sell. After it we return the profit. This method was pretty good however when further researching the problem I found a better way.

In this new version I found that using Math.min/max cut down the run time of the code, making it more efficient.