Algorithm: Max Counters

后端 未结 22 1590
孤城傲影
孤城傲影 2021-02-04 07:40

I have the following problem:

You are given N counters, initially set to 0, and you have two possible operations on them:

  • increase(X) − counter X is increa
22条回答
  •  清酒与你
    2021-02-04 08:30

    Here is an implementation in PHP:

    function solution($N, $A) {
        $output = array_fill(0, $N, 0);
        $maxCounter = 0;
        $minCounter = 0;
        foreach ($A as $number) {
            if($number === $N + 1) {
                $minCounter = $maxCounter;
            } else if($number <= $N) {
                $number--;
                if($minCounter > $output[$number]) {
                    $output[$number] = $minCounter;
                }
                $output[$number]++;
                if($output[$number] > $maxCounter) $maxCounter = $output[$number];
            }
        }
    
        foreach ($output as $index => $number) {
            if($number < $minCounter) $output[$index] = $minCounter;
        }
    
    //    var_dump($output);
        return $output;
    }
    

提交回复
热议问题