3v4l.org

run code in 300+ PHP versions simultaneously
<?php $max = 111; //265; $items = [50, 45, 30, 60, 70, 80]; function nextFitDecreasing(array $items, int $max): array { rsort($items); $result = []; foreach ($items as $item) { if (!isset($pallet) || (array_sum($pallet) + $item) > $max) { unset($pallet); $result[] = &$pallet; } $pallet[] = $item; } return $result; } function firstFitDecreasing(array $items, int $max): array { rsort($items); $result = []; foreach ($items as $item) { foreach ($result as &$pallet) { if (array_sum($pallet) + $item <= $max) { $pallet[] = $item; continue 2; } } $result[] = [$item]; } return $result; } var_export(nextFitDecreasing($items, $max)); echo "\n---\n"; var_export(firstFitDecreasing($items, $max));

preferences:
27.43 ms | 406 KiB | 5 Q