Counting bounded slice codility

后端 未结 7 1212
一个人的身影
一个人的身影 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:09

    I have provided the answer for the same question in different SO Question
    (1) For an A[n] input , for sure you will have n slices , So add at first. for example for {3,5,4,7,6,3} you will have for sure (0,0)(1,1)(2,2)(3,3)(4,4) (5,5).
    (2) Then find the P and Q based on min max comparison.
    (3) apply the Arithmetic series formula to find the number of combination between (Q-P) as a X . then it would be X ( X+1) /2
    But we have considered "n" already so the formula would be (x ( x+1) /2) - x) which is x (x-1) /2 after basic arithmetic.

    For example in the above example if P is 0 (3) and Q is 3 (7) we have Q-P is 3 . When apply the formula the value would be 3 (3-1)/2 = 3. Now add the 6 (length) + 3 .

    Then take care of Q- min or Q - max records.

    Then check the Min and Max index .In this case Min as 0 Max as 3 (obivously any one of the would match with currentIndex (which ever used to loop). here we took care of (0,1)(0,2)(1,2) but we have not taken care of (1,3) (2,3) . Rather than start the hole process from index 1 , save this number (position 2,3 = 2) , then start same process from currentindex( assume min and max as A[currentIndex] as we did while starting). finaly multiply the number with preserved . in our case 2 * 2 ( A[7],A[6]) .

    It runs in O(N) time with O(N) space.

提交回复
热议问题