Algorithm: Max Counters

后端 未结 22 1881
孤城傲影
孤城傲影 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条回答
  •  Happy的楠姐
    2021-02-04 08:37

    C++11 code:

    #include 
    
    vector solution(int N, vector &A) {
    
        vector hist(N, 0);
    
        int last_update = 0;
        int max_value = 0;
    
        for (auto i : A){
    
            if (1 <= i && i <= N){
                int& val = hist[i - 1];
    
                if (val < last_update)
                    val = last_update + 1;
                else
                    val++;
    
                if (max_value < val)
                    max_value = val;
            }
    
            if (i == (N+1)){
                last_update = max_value;
            }
    
        }
    
        replace_if(hist.begin(), hist.end(), [last_update](int x){return x < last_update;}, last_update);
    
        return hist;
    }
    

提交回复
热议问题