burtonLowel
burtonLowel

Reputation: 794

Javascript: Confused about usage of Infinity

I'm doing some practice problems to stay fresh and I've never really used Infinity before in my job. The question is:

Find maximum difference between two numbers in the given array. Also, the second number must be larger than the first one.

My solution was:

var maxProfit = function(prices) {
    let min = 0;
    let max = 0;
    for (var x = 0; x < prices.length; x++) {
        min = Math.min(min, prices[x]);
        max = Math.max(max, prices[x] - min);
    }
    return max;
};

But it comes back incorrect and I'm not sure why. When looking at the accepted solutions, one of them has the same code as me except the initialized value of min is Infinity, ( let min = Infinity ) rather than 0. I'm not really sure how or why that works.

Upvotes: 2

Views: 86

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138557

Because 0 is always smaller than any other positive number. Therefore unless you have negative prices, the minimum will be 0. You can exchange 0 with any other larger number, e.g. 1000, and even then the function might return the wrong minimum because the smallest price in the array might only be 1001. So as an initial value you can either take one of the array values (e.g. the first one), or you take Infinity cause that's greater than any other number, and thus it will never be the result unless the array is empty. And in that case, Infinity is a proper result.

Upvotes: 4

Related Questions