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:
First, an array of stock prices is defined:
let prices = [7,1,5,3,6,4]
.A function
maxProfit
is defined, which takes theprices
array as an argument.Three variables are initialized:
left
(the index of the price to buy),right
(the index of the price to sell), andmax_profit
(the maximum profit found so far).The algorithm loops through the
prices
array from left to right, comparing each price to the one to its right.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]
.If the profit is greater than the
max_profit
found so far, it becomes the newmax_profit
.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 theright
index.The
right
index is incremented by 1, and the loop continues until the end of theprices
array is reached.The
max_profit
is returned by the function.Finally, the function is called with the
prices
array as an argument, and the result is logged to the console usingconsole.log()
.