How to most efficiently increase values at a specified range in a large array and then find the largest value

后端 未结 5 877
小鲜肉
小鲜肉 2020-12-11 11:01

So I just had a programming test for an interview and I consider myself a decent programmer, however I was unable to meet time constraints on the online test (and there was

5条回答
  •  暖寄归人
    2020-12-11 11:47

    Detect local maximums while running through the instructions. The answer will be the maximum of local maximums. Please, note that the vector p must be sorted by start.

    struct Instruction
    {
        size_t start, stop;
        value_t value;
    
        bool operator > (const Instruction& b) const
        {
            return stop > b.stop;
        }
    };
    
    template
    value_t do_work(const Ti&& b, const Ti&& e)
    {
        value_t result = 0;
        value_t local = 0;
    
        auto q = priority_queue, 
                     greater>();
    
        for (auto i=b; i!=e; ++i)
        {
            q.push(*i);
            if (q.top().stop < i->start)
            {
                if (local > result)result = local;
                do
                {
                    local -= q.top().value;
                    q.pop();
                } while (q.top().stop < i->start);
            }
    
            local += i->value;
        }
    
        return max(local, result);
    }
    
    int main()
    {
        vector p = { 
            {0,3,143}, {2,4,100}, {2,2,100}, 
            {3,5,1000}, {4,4,500} 
        };
    
        cout << do_work(begin(p),end(p)) << endl;
    
        return 0;
    }
    

提交回复
热议问题