Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 12, 2022 07:44 pm GMT

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.

Image description

Image description

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:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To