Minimum value of maximum values in sub-segments … in O(n) complexity

后端 未结 3 465
半阙折子戏
半阙折子戏 2020-12-14 03:33

I interviewed with Amazon a few days ago. I could not answer one of the questions the asked me to their satisfaction. I have tried to get the answer after the interview but

3条回答
  •  爱一瞬间的悲伤
    2020-12-14 04:21

    I implemented (and commented) templatetypedef's answer in C#.

    n is array length, k is window size.

        public static void printKMax(int[] arr, int n, int k)
        {
            Deque qi = new Deque(); 
            int i;
    
            for (i=0 ; i < k ; i++) // The first window of the array
            {
                while ((qi.Count > 0) && (arr[i] >= arr[qi.PeekBack()]))
                {
                    qi.PopBack();
                }
                qi.PushBack(i);
            }
    
            for(i=k ; i < n ; ++i)
            {
                Console.WriteLine(arr[qi.PeekFront()]); // the first item is the largest element in previous window. The second item is its index.
    
                while (qi.Count > 0 && qi.PeekFront() <= i - k) 
                {
                    qi.PopFront(); //When it's out of its window k 
                }
                while (qi.Count>0 && arr[i] >= arr[qi.PeekBack()]) 
                {
                    qi.PopBack();
                }
                qi.PushBack(i);
            }
            Console.WriteLine(arr[qi.PeekFront()]);
        }
    

提交回复
热议问题