Problem: Given an array of stock prices over time, need to figure out the best buy and sell price so that we get the maximum profit. The selling should occur after buying of the stock.
Let's go through the solution for the above problem statement using javascript.
const maxStockProfit = arr => {
let maxProfit = 0; // initialize max
let lowestPrice = arr[0];
for(let i = 1; i < arr.length; i++){
let price = arr[i];
if(price < lowestPrice) lowestPrice = price;
let profit = price  lowestPrice;
maxProfit = Math.max(profit, maxProfit);
}
return maxProfit;
}
The solution is quite simple where for each iteration over the array we compare the current item with the lowest price and check for the maximum profit by substracting lowest price with current price and then update the maximum profit based on last profit and current profit.
Categories








