Best time to buy and sell stock

Tried to unravel one other query from leetcode involing purchase and promoting a inventory at a particular value. The main points are outlined beneath.

Want some steerage as a result of the code dosen’t work however i am certain my logic is right right here. The feedback define what i’m doing step-by-step for this query.

Image description

var maxProfit = perform(costs) {
    const purchase = Math.min(costs);                   //discovering the bottom worth/ purchase value
    const index = costs.indexOf(purchase);              //get the index of the purchase value
    let temp = [];                                  //momentary array to retailer attainable promote costs
    for (let i=index; i<costs.length-1; i++) {
        if (costs[i] > costs[index]) {            //iterate for each aspect in costs later than purchase value
            temp.push(costs[i]);                   //add the values to the temp array
    const promote = Math.max(temp);                    //get the very best worth on this temp array
    const revenue = sell-buy;                        //get revenue 
    if (promote == null) {
        return 0;
    return revenue;
Enter fullscreen mode

Exit fullscreen mode

Add a Comment

Your email address will not be published. Required fields are marked *