Algorithm: Max Counters

后端 未结 22 1603
孤城傲影
孤城傲影 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-04 08:26

    A 100/100 solution in php

    function solution($N, $A){
        $cond     = $N + 1;
        $cur_max  = 0;
        $last_upd = 0;
        $cnt_arr  = array();
        $cnt      = count($A);
        for($i = 0; $i < $cnt; $i++){
            $cur = $A[$i];
            if($cur == $cond){
                $last_upd = $cur_max;
            }
            else{
                $pos = $cur - 1;
                if(!isset($cnt_arr[$pos])){
                    $cnt_arr[$pos] = 0;
                }
                if($cnt_arr[$pos] < $last_upd){
                    $cnt_arr[$pos] = $last_upd + 1;
                }
                else{
                    $cnt_arr[$pos] ++;
                }
                if($cnt_arr[$pos] > $cur_max){
                    $cur_max = $cnt_arr[$pos];
                }
            }
        }
        for($i = 0; $i < $N; $i++){
            if(!isset($cnt_arr[$i])){
                $cnt_arr[$i] = 0;
            }
            if($cnt_arr[$i] < $last_upd){
                $cnt_arr[$i] = $last_upd;
            }
        }
        return $cnt_arr;
    }
    

提交回复
热议问题