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

后端 未结 5 875
小鲜肉
小鲜肉 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:58

    The solution is to determine where the ranges overlap. The code needs to maintain a list of ranges, and as each input line is processed, the list must be updated. Assuming that there are only a small number of ranges compared with the number of items in the array, it will be much faster to process a table of ranges than naively update the array.

    For example, lets's say that the array has ten million entries, and you were given two instructions

    [0,5000000] 50
    [4000000,6000000] 100
    

    The naive solution will write 17 million entries in the array (10 million to initialize the array, and another 7 million to process the two instructions). But you can determine instantly that the max value is 150 because the two ranges overlap.

提交回复
热议问题