The Wayback Machine - https://web.archive.org/web/20211227224017/https://www.geeksforgeeks.org/replace-every-array-element-with-maximum-of-k-next-and-k-previous-elements/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Replace every array element with maximum of K next and K previous elements

  • Last Updated : 27 Dec, 2021

Given an array arr, the task is to replace each array element by the maximum of K next and K previous elements.

Example:

Input: arr[] = {12, 5, 3, 9, 21, 36, 17}, K=2
Output: 5 12 21 36 36 21 36

Input: arr[] = { 13, 21, 19}, K=1
Output: 21, 19, 21 



Naive Approach: Follow the below steps to solve this problem:

  1. Traverse the array from i=0 to i<N and for each element:
    • Run another loop from j=i-K to j<=i+K, and change arr[i] to the maximum of K next and K previous elements.
  2. Print the array after the above loop ends.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
  
#include <iostream>
#include <limits.h>
#include <math.h>
using namespace std;
  
// Function to update the array
// arr[i] = maximum of prev K and next K elements.
void updateArray(int arr[], int N, int K)
{
  
    int start, end;
    for (int i = 0; i < N; i++) {
        int mx = INT_MIN;
  
        // Start limit is max(i-K, 0)
        start = max(i - K, 0);
  
        // End limit in min(i+K, N-1)
        end = min(i + K, N - 1);
        for (int j = start; j <= end; j++) {
  
            // Skipping the current element
            if (j == i) {
                continue;
            }
            mx = max(arr[j], mx);
        }
  
        cout << mx << ' ';
    }
}
  
// Driver Code
int main()
{
    int arr[] = { 12, 5, 3, 9, 21, 36, 17 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 2;
  
    updateArray(arr, N, K);
}
Output
5 12 21 36 36 21 36 

Time Complexity: O(N*N)
Auxiliary Space: O(1)

Efficient Approach: A segment tree can be used to solve this problem. So, construct a range max segment tree, where:

  • Leaf Nodes are the elements of the input array.  
  • Each internal node represents the maximum of all of its children.

Now, after building the segment tree, find the maximum from (i-K) to (i-1), say left and the maximum of (i+1) to (i+K), say right using query on this segment tree. Replace arr[i] with the maximum of left and right.

Below is the implementation of the above approach:

C++




// C++ code for the above approach
  
#define MAXN 500001
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to build the tree
void buildTree(vector<int>& arr,
               vector<int>& tree, int s,
               int e, int index)
{
  
    // Leaf Node
    if (s == e) {
        tree[index] = arr[s];
        return;
    }
  
    // Finding mid
    int mid = (s + e) / 2;
  
    buildTree(arr, tree, s,
              mid, 2 * index + 1);
    buildTree(arr, tree, mid + 1,
              e, 2 * index + 2);
  
    // Updating current node
    // by the maximum of its children
    tree[index]
        = max(tree[2 * index + 1],
              tree[2 * index + 2]);
}
  
// Function to find the maximum
// element in a given range
int query(vector<int>& tree, int s,
          int e, int index, int l,
          int r)
{
  
    if (l > e or r < s) {
        return INT_MIN;
    }
  
    if (l <= s and r >= e) {
        return tree[index];
    }
  
    int mid = (s + e) / 2;
  
    int left = query(tree, s, mid,
                     2 * index + 1, l, r);
    int right
        = query(tree, mid + 1, e,
                2 * index + 2, l, r);
  
    return max(left, right);
}
  
// Function to replace each array element by
// the maximum of K next and K previous elements
void updateArray(vector<int>& arr, int K)
{
  
    // To store the segment tree
    vector<int> tree(MAXN);
  
    int N = arr.size();
    buildTree(arr, tree, 0, N - 1, 0);
  
    for (int i = 0; i < N; ++i) {
        // For 0th index only find
        // the maximum out of 1 to i+K
        if (i == 0) {
            cout << query(tree, 0, N - 1, 0, 1,
                          min(i + K, N - 1))
                 << ' ';
            continue;
        }
  
        // For (N-1)th index only find
        // the maximum out of 0 to (N-2)
        if (i == N - 1) {
            cout << query(tree, 0, N - 1,
                          0, max(0, i - K),
                          N - 2);
            continue;
        }
  
        // Maximum from (i-K) to (i-1)
        int left = query(tree, 0, N - 1,
                         0, max(i - K, 0),
                         i - 1);
  
        // Maximum from (i+1) to (i+K)
        int right = query(tree, 0,
                          N - 1, 0, i + 1,
                          min(i + K, N - 1));
  
        cout << max(left, right) << ' ';
    }
}
  
// Driver Code
int main()
{
    vector<int> arr = { 12, 5, 3, 9,
                        21, 36, 17 };
    int K = 2;
  
    updateArray(arr, K);
}
Output
5 12 21 36 36 21 36

Time Complexity: O(NlogN)
Auxiliary Space: O(1)




My Personal Notes arrow_drop_up

Start Your Coding Journey Now!