Counting bounded slice codility

后端 未结 7 1209
一个人的身影
一个人的身影 2021-02-08 13:11

I have recently attended a programming test in codility, and the question is to find the Number of bounded slice in an array..

I am just giving you breif explanation of

7条回答
  •  太阳男子
    2021-02-08 13:59

    HINTS

    Others have explained the basic algorithm which is to keep 2 pointers and advance the start or the end depending on the current difference between maximum and minimum.

    It is easy to update the maximum and minimum when moving the end.

    However, the main challenge of this problem is how to update when moving the start. Most heap or balanced tree structures will cost O(logn) to update, and will result in an overall O(nlogn) complexity which is too high.

    To do this in time O(n):

    1. Advance the end until you exceed the allowed threshold
    2. Then loop backwards from this critical position storing a cumulative value in an array for the minimum and maximum at every location between the current end and the current start
    3. You can now advance the start pointer and immediately lookup from the arrays the updated min/max values
    4. You can carry on using these arrays to update start until start reaches the critical position. At this point return to step 1 and generate a new set of lookup values.

    Overall this procedure will work backwards over every element exactly once, and so the total complexity is O(n).

    EXAMPLE

    For the sequence with K of 4:

    4,1,2,3,4,5,6,10,12
    

    Step 1 advances the end until we exceed the bound

    start,4,1,2,3,4,5,end,6,10,12
    

    Step 2 works backwards from end to start computing array MAX and MIN. MAX[i] is maximum of all elements from i to end

    Data = start,4,1,2,3,4,5,end,6,10,12
    MAX  = start,5,5,5,5,5,5,critical point=end -
    MIN  = start,1,1,2,3,4,5,critical point=end -
    

    Step 3 can now advance start and immediately lookup the smallest values of max and min in the range start to critical point.

    These can be combined with the max/min in the range critical point to end to find the overall max/min for the range start to end.

    PYTHON CODE

    def count_bounded_slices(A,k):
        if len(A)==0:
            return 0
        t=0
        inf = max(abs(a) for a in A)
        left=0
        right=0
        left_lows = [inf]*len(A)
        left_highs = [-inf]*len(A)
        critical = 0
        right_low = inf
        right_high = -inf
        # Loop invariant
        #  t counts number of bounded slices A[a:b] with a

提交回复
热议问题