LC: 121 Best Time To Buy and Sell Stock I

LC: 121 Best Time To Buy and Sell Stock I

ยท

2 min read

Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Here's a breakdown of how the code works:

  1. First, an array of stock prices is defined: let prices = [7,1,5,3,6,4].

  2. A function maxProfit is defined, which takes the prices array as an argument.

  3. Three variables are initialized: left (the index of the price to buy), right (the index of the price to sell), and max_profit (the maximum profit found so far).

  4. The algorithm loops through the prices array from left to right, comparing each price to the one to its right.

  5. If the price to the right is higher than the price to the left, a profit can be made by buying at the left price and selling at the right price. The profit is calculated as prices[right] - prices[left].

  6. If the profit is greater than the max_profit found so far, it becomes the new max_profit.

  7. If the price to the right is not higher than the price to the left, it means the left price is not a good choice to buy, so the algorithm moves the left index to the right index.

  8. The right index is incremented by 1, and the loop continues until the end of the prices array is reached.

  9. The max_profit is returned by the function.

  10. Finally, the function is called with the prices array as an argument, and the result is logged to the console using console.log().

Did you find this article valuable?

Support TopGun by becoming a sponsor. Any amount is appreciated!

ย