An Interest In:
Web News this Week
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
May 12, 2022 07:44 pm GMT
Original Link: https://dev.to/juliansjy/best-time-to-buy-and-sell-stock-1mnh
Best time to buy and sell stock
Tried to solve another question from leetcode involing buy and selling a stock at a specific price. The details are outlined below.
Need some guidance because the code dosen't work but i'm sure my logic is correct here. The comments outline what i am doing step by step for this question.
var maxProfit = function(prices) { const buy = Math.min(prices); //finding the lowest value/ buy price const index = prices.indexOf(buy); //get the index of the buy price let temp = []; //temporary array to store possible sell prices for (let i=index; i<prices.length-1; i++) { if (prices[i] > prices[index]) { //iterate for every element in prices later than buy price temp.push(prices[i]); //add the values to the temp array } } const sell = Math.max(temp); //get the highest value in this temp array const profit = sell-buy; //get profit if (sell == null) { return 0; } return profit;};
Original Link: https://dev.to/juliansjy/best-time-to-buy-and-sell-stock-1mnh
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To