not sure why this solution is returning undefined (array algo)

116 Views Asked by At

the problem is as follows :

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

My solutions keeps returning undefined and I'm not sure why. Any ideas on how to fix this to make it correct?

var maxProfit = function(prices) {
    var minNum = Math.min(...prices);
    var indMin = prices.indexOf(minNum);
    for (var ind = 0; ind > indMin && ind < prices.length ; ind++){
        var maxNum = Math.max(...prices);
        var profit = maxNum - minNum
    return profit

    }}

thanks!

1

There are 1 best solutions below

0
On

Your loop is stopping before the first iteration. The condition to enter the loop is ind > indMin && ind < prices.length. On the first iteration, ind == 0 and indMin is at least 0. Since ind > indMin cannot be true, the loop ends immediately.

You also shouldn't return inside the loop. You need to keep searching for better solutions, and return at the end once you've maximized the profit.

You can't use the minimum price that you find at the beginning, because it could be after all the prices that you'd want to sell at to get a profit.

Use nested loops. One loop selects a purchase price, the inner loop then finds the sale price after that with the best profit.

let profit = 0;
for (let pindex = 0; pindex < prices.length - 1; pindex++) {
    for (let sindex = pindex + 1; sindex < prices.length; sindex++) {
        if (prices[sindex] - prices[pindex]) > profit) {
            profit = prices[sindex] - prices[pindex];
        }
    }
}

If you want to use Math.max(), you can replace the inner loop with that. Use slice() to get all the prices after the purchase date.

let profit = 0;
prices.forEach((purchase_price, i) => {
    let max_sale_price = Math.max(...prices.slice(i+1));
    profit = Math.max(profit, max_sale_price - purchase_price);
});