Solve LeetCode problem #121 Best Time to Buy and Sell Stock

In this article, we will be discussing the solution to the LeetCode problem #121 - Best Time to Buy and Sell Stock.

Problem Overview

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

For instance:

1- Example 1:
2 - Input: `prices = [7,1,5,3,6,4]`
3 - Output: `5`
4 - Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
5 Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
6- Example 2:
7 - Input: `prices = [7,6,4,3,1]`
8 - Output: `0`
9 - Explanation: In this case, no transactions are done, and the max profit = 0.

Solution

You can also check the video solution.

The idea of stocks are that you buy them on low price and sell that on high price. Basically we just need to find the lowest price and the highest price after that day.

The algorithm is as follows:

  • Initialize the max profit and the lowest price to 0
  • Loop over the array
    • Check if the index is 0
      • If yes then set the lowest price to the current price and return
      • If not then
        • Calculate the profit by subtracting the current price from the lowest prices
        • Set the lowest price to the minimum of the current price and the lowest prices
        • Set the max profit to the maximum of the profit and the max profit
  • Return the max profit
1/**
2 * @param {number[]} prices
3 * @return {number}
4 */
5var maxProfit = function (prices) {
6 let maxProfit = 0
7 let lowestPrice = 0
8
9 prices.forEach((price, index) => {
10 if (!index) {
11 lowestPrice = price
12 return
13 }
14
15 const profit = price - lowestPrice
16 lowestPrice = Math.min(lowestPrice, price)
17 maxProfit = Math.max(profit, maxProfit)
18 })
19
20 return maxProfit
21}

Shameless Plug

I have made an Xbox landing page clone with React and Styled components. I hope you will enjoy it. Please consider like this video and subscribe to my channel.

That's it for this blog. I have tried to explain things simply. If you get stuck, you can ask me questions.

Contacts

Blogs you might want to read:

Videos might you might want to watch:

Previous PostSolve LeetCode problem #125 Valid Palindrome
Next PostSolve LeetCode problem #217 Contains Duplicate