from given array of n elements find the maximum element for each consecutive subarray of k elements.

Q: from given array of n elements find the maximum element for each consecutive sub-array of k elements. 
eg. 
array=[6,5,4,3,2,1] 
k=3 
ans=6 5 4 3 
explanation:
6 from array [6,5,4] 
5 from array [5,4,3]

4 from array [4,3,2]

3 from array [3,2,1]

A: 

void max_element_of_subarr(int a[], int n, int k)
{
    for(int m=0; m<n; ++m)
        cout << a[m] << " ";
    cout << endl;

    int* b = new int[n-k+1];
    int i = 0;
    while (i <= n - k)
    {
        int max = a[i];
        int j   = i;

        if ((i>0) && b[i-1] > i && b[i-1] <(i+k))
        {
            j   = b[i-1];
            max = a[j];
        }

        b[i]=j;
        for (j=j+1;j <i+k; ++j)
        {
            if (max < a[j])
            {
                max = a[j];
                b[i]= j;
            }
        }

        ++i;
    }

    for(int m=0; m<n-k+1; ++m)
        cout << a[b[m]] << " ";

    delete [] b;
    cout << endl;
}

测试用例:

            int a[] = {6,9,10,3,5,7,2,11};
            max_element_of_subarr(a, sizeof(a)/sizeof(a[0]), 3);

            int b[] = {6,5,4,3,2,1};
            max_element_of_subarr(b, sizeof(b)/sizeof(b[0]), 3);

            int c[] = {6,9,10,3,11,7,2,12,6,13};
            max_element_of_subarr(c, sizeof(c)/sizeof(c[0]), 4);

测试结果:

6   9  10 3 5 7 2 11
10 10 10 7 7 11

6 5 4 3 2 1
6 5 4 3

6   9  10  3  11  7  2  12  6  13
10 11 11 11 12 12 13

A2:看到一个方法,比我自己写的这个更简洁,转过来(已经用上面的测试用例跑过,全部通过)

Key idea: a deque whose front will always hold maximum in current window.

View Code
 1 void maxInWindow(int* arr, int length, int k)
 2 {
 3     std::deque<int> Qi(k);
 4     int i;
 5     for(i = 0; i < k; i++)
 6     {
 7         while(!Qi.empty() && arr[i] >= arr[Qi.back()])
 8         {
 9             Qi.pop_back();
10         }
11         Qi.push_back(i);
12     }
13 
14     for( ; i < length; i++)
15     {
16         std::cout << arr[Qi.front()] << " ";
17         while(!Qi.empty() && (i - k) >= Qi.front())
18         {
19             Qi.pop_front();
20         }
21 
22         while(!Qi.empty() && arr[i] >= arr[Qi.back()])
23         {
24             Qi.pop_back();
25         }
26         Qi.push_back(i);
27     }
28     std::cout << arr[Qi.front()] << std::endl;
29 }
原文地址:https://www.cnblogs.com/yayagamer/p/2970546.html