// Print all elements in an array
function printArray(arr: number[]): void {
console.log(arr.join(" "));
}
// Calculate how many days you must wait for a warmer temperature
function numberOfDaysToWait(temperatures: number[]): number[] {
const size: number = temperatures.length;
const result: number[] = new Array(size).fill(0);
const stack: number[] = []; // stack of indices
for (let i: number = 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: number = stack.pop() as number;
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;
}
// Example usage:
const temperatures: number[] = [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: number[] = numberOfDaysToWait(temperatures);
printArray(result);
/*
run:
1 3 2 1 1 0 0 0
*/