DEV Community


Posted on

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;
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

vcastroi profile image
Victor Castro

problem is lowest price should not be your starting point, if in the 1st example the last price were to be 1, you would miss on 6-3=3 before it

you need 2 for cycles one inside the other, and calculate profit for each one if inner index is grater then outer index, keep track of the greatest profit.

or single for cycle and search max on the subset of items where index greater than the current one.

juliansjy profile image
julian Author

ahhh... okok i understand. Didn't consider that initially.