## DEV Community is a community of 867,901 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

julian

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.

``````var maxProfit = function(prices) {
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;
};
``````

## Discussion (2)

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.

julian

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