Are you looking for the most efficient way to solve LeetCode's Best Time to Buy and Sell Stock problem with JavaScript? Look no further!
By the end of this post, you will have a solid understanding of how to approach this problem and how to write a solution that maximizes your profit while minimizing your code.
Before we dive into the solution, let's first take a look at the problem statement.
The Best Time to Buy and Sell Stock problem asks us to find the maximum profit we can make by buying and selling a single stock.
We are given an array of stock prices, where the ith element represents the price of the stock on the ith day. We are allowed to buy and sell the stock only once, and we must do so before the end of the day (i.e. we cannot hold the stock overnight).
To solve this problem, we will use a simple yet effective approach.
First, we will iterate through the array of stock prices and keep track of the minimum price we have seen so far.
This will represent the lowest price we can buy the stock for.
Then, on each iteration, we will calculate the potential profit we could make if we were to sell the stock at the current price.
If this profit is greater than the maximum profit we have seen so far, we will update the maximum profit with the new value.
Here is the JavaScript code for this solution:
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let minPrice = Number.MAX_SAFE_INTEGER;
let profit = 0;
for (i = 0; i < prices.length; i++) {
minPrice = Math.min(prices[i], minPrice);
profit = Math.max(profit, prices[i] - minPrice);
}
return profit;
};
No comments:
Post a Comment