Counting bounded slice codility

后端 未结 7 1211
一个人的身影
一个人的身影 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 14:06

    Now codility release their golden solution with O(N) time and space. https://codility.com/media/train/solution-count-bounded-slices.pdf

    if you still confused after read the pdf, like me.. here is a very nice explanation

    The solution from the pdf:

    def boundedSlicesGolden(K, A):
    N = len(A)
    
    maxQ = [0] * (N + 1)
    posmaxQ = [0] * (N + 1)
    minQ = [0] * (N + 1)
    posminQ = [0] * (N + 1)
    
    firstMax, lastMax = 0, -1
    firstMin, lastMin = 0, -1
    j, result = 0, 0
    
    for i in xrange(N):
        while (j < N):
            # added new maximum element
            while (lastMax >= firstMax and maxQ[lastMax] <= A[j]):
                lastMax -= 1
            lastMax += 1
            maxQ[lastMax] = A[j]
            posmaxQ[lastMax] = j
    
            # added new minimum element
            while (lastMin >= firstMin and minQ[lastMin] >= A[j]):
                lastMin -= 1
            lastMin += 1
            minQ[lastMin] = A[j]
            posminQ[lastMin] = j
    
            if (maxQ[firstMax] - minQ[firstMin] <= K):
                j += 1
            else:
                break
        result += (j - i)
        if result >= maxINT:
            return maxINT
        if posminQ[firstMin] == i:
            firstMin += 1
        if posmaxQ[firstMax] == i:
            firstMax += 1
    return result
    

提交回复
热议问题