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

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

    It isn't completely clear from you question whether the large array contains all zeros at the start, or whether you are given a large array with initial values, but similar methods can be used in both cases:

    A) Large array of zeros

    First of all, in this case there is no need to actually create the large array, or do anything with it.

    Given these ranges and values:

    [0, 3] 143
    [2, 4] 100
    [2, 2] 100

    Create a list, where every low index is stored with the value, and every high index (plus 1) is stored with the inverse of the value:

    {0, +143} {4, -143} {2, +100} {5, -100} {2, +100} {3, -100}

    Then sort this list (and preferably merge values with the same index):

    {0, +143} {2, +200} {3, -100} {4, -143} {5, -100}

    Then, iterate over the list, keep a running total, and find the maximum value and its start and end index:

               total  
    {0, +143}   143  
    {2, +200}   343   <-- max  
    {3, -100}   243   <-- end  
    {4, -143}   100  
    {5, -100}     0  
    

    So the maximum value is 343, and its range is index 2 ~ 3 (so really only position 2).

    The complexity of this algorithm is linear to the number of ranges M, but not influenced by the size of the large array N, so O(M).

    B) Large array with initial values

    If you are given an array with inital values, e.g.:

    [300, 200, 400, 600, 700]

    any element could still have the largest value after the values in the ranges have been increased, so in the end you have to iterate over every element in the array to find the maximum value.

    However, you can avoid having to actually increase any values in the array, or iterate over the array more than once, by creating the same list as above:

    {0, +143} {2, +200} {3, -100} {4, -143} {5, -100}

    and then iterating over the array to find the maximum value, while keeping a running total of the additional values, and adding these to the values while comparing with the maximum value:

                  total
    0: {0, +143}   143   value: 300 + 143 = 443  
    1: no change   143   value: 200 + 143 = 343  
    2: {2, +200}   343   value: 400 + 343 = 743  
    3: {3, -100}   243   value: 600 + 243 = 843   <-- max  
    4: {4, -143}   100   value: 700 + 100 = 800   <-- end  
    5: {5, -100}     0  
    

    So the maximum value is 843, and its range is index 3 ~ 4 (so really only position 3).

    The complexity of this algorithm is linear to the size of the large array N, and linear to the number of ranges M, or O(N+M), but assuming that N is much greater than M, this is ~ O(N).

提交回复
热议问题