Today's algorithm is a very common one: Best Time to Buy and Sell Stock

Say you have an array for which the i-th element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one.

For example, let's say you were given the array `[8, 1, 4, 2, 6, 5]`

as the input, which is supposed to represent the price of a stock on each day. The best profit you could make would be by buying stock on the second day (index 1), when the price was 1, and selling it on the fifth day (index 4), when the price was 6, for a total max profit of 5 (6 - 1 = 5).

This problem, and variations on it, come up all the time. The first time I saw it, my instinct was to solve it by comparing the values at every price, an approach which would take a long time. However, there's a much more straightforward way to solve this problem, which I'll be discussing in this post.

## Approaching the Problem

I think one of the hardest parts of this problem is visualizing it. To help aid that, I'll draw a graph based on a price array of `[8, 1, 4, 2, 6, 5]`

.

The maximum profit is found by finding the smallest number (the lowest valley), which is the price you'd buy the stock at, and then the largest number that comes after it (the tallest peak).

What if, you may be wondering, a small number comes up on a later day, but the maximum profit after that is not very big? For example, let's say the inputted array was `[4, 2, 9, 7, 1, 2]`

. The graph of prices would look like this:

Even though the price on day 5 is smaller than the price on day 2, the maximum profit would come from buying on day 2 and selling on day 3. In our coded solution, therefore, we should always be looking for a new minimum price, but we also should only update the maximum profit when a new maximum profit is found.

To solve this problem, therefore, we should keep track of the minimum price, and update it only when a smaller price is found. We also should keep track of the profit at every point, which is found by subtracting the minimum price from the current price--if that number is larger than the existing maximum profit, we'll update the maximum profit. Because we will be solving this problem by only walking through the array one time, we'll be doing it in "one pass".

## Coding the Solution to the Stock Problem

As we discussed in the approach, we should be keeping track of the minimum price and the maximum profit, which we'll store in variables. We can initialize the minimum price to be the first price in the `prices`

array, and the max profit to be 0. We also know we'll want to return the maximum profit at the end of the function, so we can include the return statement now.

```
function maxProfit(prices) {
let minPrice = prices[0];
let maxProfit = 0;
//...
return maxProfit;
}
```

We'll be solving this problem in one pass, which means we can have a for loop that goes from the start of the `prices`

array to the end.

At each price in the array, we'll want to check if its price is smaller than the current `minPrice`

. If it is, we'll set `minPrice`

to equal the current price we're on, which would be `prices[i]`

```
function maxProfit(prices) {
let minPrice = prices[0];
let maxProfit = 0;
for (let i = 0; i < prices.length; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i];
}
//...
}
return maxProfit;
}
```

The other thing we want to check for is if the difference between the current price and the minimum price is larger than the maximum profit. If it is, we'll want to set `maxProfit`

equal to the difference between `prices[i]`

(the current price) and `minPrice`

(the smallest price we've seen).

```
function maxProfit(prices) {
let minPrice = prices[0];
let maxProfit = 0;
for (let i = 0; i < prices.length; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i];
} else if (prices[i] - minPrice > maxProfit) {
maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
}
```

This solution solves the algorithm using O(1) space (constant space) and O(n) time (linear time). The reason it's constant space is that the only new variables we're creating store integers--they're not storing entirely new arrays of the size of `prices`

. The reason it's linear time is that we go through every element in the `prices`

array (of size `n`

) to check it, but only go through it once.

## Going Through an Example

To see how this algorithm works with an example, we can use the prices array `[4, 2, 9, 1, 2]`

.

We'll start by setting `minPrice`

equal to `prices`

at 0, which is 4, and `maxProfit`

equal to 0.

Now we'll enter the for loop, starting with index 0, 4. 4 is not less than the minimum price, and 4 minus the minimum price is not larger than the maximum profit, so we don't need to update anything.

Now we're onto index 1, which has a value of 2. This time, 2 is less than the minimum price, so we'll update the minimum price to equal 2.

We're now on index 2, which has a value of 9. 9 is not smaller than the minimum price, so we don't update the minimum price. However, the difference between 9 and the minimum price is larger than the maximum profit, so we can update the maximum profit.

We're now on index 3, which has a value of 1. 1 is smaller than the minimum price, so we'll update the minimum price.

We're now on the last index, which has a value of 2. 2 is not smaller than the minimum price, so we won't update it. And the difference between 2 and the minimum price is not larger than the existing maximum profit, so we won't update that either.

Since the for loop is done, we'll return the maximum profit we found, which was 7.

--

Please let me know if you have any questions or other approaches to this problem!

## Top comments (1)

This is the best explanation I've seen for how to approach this problem and visualizing the sliding door technique. Thank you!