<?php
function printArray(array $arr): void {
foreach ($arr as $n) {
echo $n . " ";
}
echo PHP_EOL;
}
function numberOfDaysToWait(array $temperatures): array {
$size = count($temperatures);
$result = array_fill(0, $size, 0);
$stack = []; // stack of indices
for ($i = 0; $i < $size; $i++) {
while (!empty($stack) && $temperatures[$i] > $temperatures[end($stack)]) {
$idx = array_pop($stack);
$result[$idx] = $i - $idx;
}
$stack[] = $i; // push index
}
// remaining indices already default to 0
return $result;
}
$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
$result = numberOfDaysToWait($temperatures);
printArray($result);
/*
run:
1 3 2 1 1 0 0 0
*/