1

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!

st123
  • 246
  • 3
  • 14
  • 1
    My first wild guess would be the code is not going inside the `for`, that's why it returns `undefined`. – norbitrial Sep 30 '20 at 19:27
  • 1
    Why are you returning inside the loop? And why doens't the loop use `ind`? – Barmar Sep 30 '20 at 19:28
  • @Barmar should I use filter instead to find the max number after a certain index? – st123 Sep 30 '20 at 19:34
  • Shouldn't you be getting the max of all the elements after `ind`? Otherwise you might try to sell at a price that was before you bought. – Barmar Sep 30 '20 at 19:35
  • I think your whole algorithm is wrong. What if the minimum price is the last day? You need to use an earlier price as the purchase price. – Barmar Sep 30 '20 at 19:37
  • I'm new to this and I'm just trying to learn.. can you explain what you would do instead – st123 Sep 30 '20 at 19:38

1 Answers1

0

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);
});
Barmar
  • 741,623
  • 53
  • 500
  • 612