Untitled

 avatar
unknown
php
a year ago
2.7 kB
6
Indexable
<?php

    class Solution
    {
        public $commercialDurations = [];
        public $interval = 0;
        private $bestPair = null;
        
        function __construct($commercialDurations, $interval) {
            $this->commercialDurations = $commercialDurations;
            $this->interval = $interval;
            $this->setBestPairs();
        }

        public function setBestPairs() {
            $longerDuration = 0;
            $longerCommercials = [];

            for ($x = 0; $x < count($this->commercialDurations) - 1; $x++) {
                for ($y = $x + 1; $y < count($this->commercialDurations); $y++) {
                    $pair = array($this->commercialDurations[$x], $this->commercialDurations[$y]);
                    $combinedDuration = $this->commercialDurations[$x] + $this->commercialDurations[$y];

                    if ($combinedDuration === $this->interval) {
                        $longerDuration = $combinedDuration;
                        array_push($longerCommercials, $pair);
                    } else if ($combinedDuration > $longerDuration && $combinedDuration < $this->interval) {
                        $longerDuration = $combinedDuration;
                        $longerCommercials = [];
                        array_push($longerCommercials, $pair);
                    } else if ($combinedDuration === $longerDuration) {
                        array_push($longerCommercials, $pair);
                    }
                }
            }
            
            $bestPair = [];
            if (count($longerCommercials) > 1) {
                $bestPair = $this->fixMultiplePairs($longerCommercials);
            } else {
                $bestPair = $longerCommercials[0];
            }

            $this->setBestPair($bestPair);
        }


        public function getBestPair() {
            return $this->bestPair;
        }

        private function setBestPair($pair) {
            $this->bestPair = $pair;
        }

        private function fixMultiplePairs($pairs) {
            $longer = 0;
            $bestPair = [];
            foreach ($pairs as $pair) {
                foreach ($pair as $commercial) {
                    if ($commercial > $longer) {
                        $longer = $commercial;
                        $bestPair = $pair;
                    }
                }
            }

            return $bestPair;
        }
    }

    $solution = new Solution([17, 18, 14, 11, 23, 29, 24, 25], 26);
    $bestPair = $solution->getBestPair();

    $solution = new Solution([17, 18, 14, 11, 23, 29, 24, 25], 44);
    $bestPair = $solution->getBestPair();
?>
Editor is loading...
Leave a Comment