How to get the number of days needed to wait after a day (a[i]) gets warmer given an array of temperatures in JavaScript

1 Answer

0 votes
// Print all elements in an array
function printArray(arr) {
    console.log(arr.join(" "));
}

// Calculate how many days you must wait for a warmer temperature
function numberOfDaysToWait(temperatures) {
    const size = temperatures.length;
    const result = new Array(size).fill(0);
    const stack = []; // stack of indices

    for (let i = 0; i < size; i++) {
        // While the current temperature is warmer than the temperature
        // at the index stored at the top of the stack:
        while (stack.length > 0 && temperatures[i] > temperatures[stack[stack.length - 1]]) {
            const index = stack.pop();
            result[index] = i - index;
        }

        // Push the current index onto the stack
        stack.push(i);
    }

    // Remaining indices in the stack have no warmer future day
    // (result already contains zeros)
    return result;
}

// usage:
const temperatures = [82, 84, 81, 58, 85, 89, 75, 71];

// 82 -> 84 = 1
// 84 -> 81 -> 58 -> 85 = 3
// 81 -> 58 -> 85 = 2
// 58 -> 85 = 1
// 85 -> 89 = 1
// 89 -> 75 -> 71 = 0
// 75 -> 71 = 0

const result = numberOfDaysToWait(temperatures);

printArray(result);



/*
run:

1 3 2 1 1 0 0 0 

*/

 



answered 15 hours ago by avibootz

Related questions

...