How to find maximum of each subarray of some fixed given length in a given array

后端 未结 6 1912
天涯浪人
天涯浪人 2021-02-14 16:41

We are given an array of n elements and an integer k. Suppose that we want to slide a window of length k across the array, reporting the largest value contained in each window.

6条回答
  •  萌比男神i
    2021-02-14 17:00

    You can achieve O(n) complexity by using Double-ended queue.

    Here is C# implementation

        public static void printKMax(int[] arr, int n, int k)
        {
            Deque qi = new Deque();
            int i;
            for (i=0;i< k; i++) // 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 front item is the largest element in previous window.
                while (qi.Count > 0 && qi.PeekFront() <= i - k) // this is where the comparison is happening!
                {
                    qi.PopFront(); //now it's out of its window k 
                }
                while(qi.Count>0 && arr[i]>=arr[qi.PeekBack()]) // repeat
                {
                    qi.PopBack();
                }
                qi.PushBack(i);
            }
    
            Console.WriteLine(arr[qi.PeekFront()]);
        }
    

提交回复
热议问题