# Python code for the above approach
import sys
MAXN = 500001
# Function to build the tree
def buildTree(arr, tree, s, e, index):
# Leaf Node
if (s == e):
tree[index] = arr[s]
return
# Finding mid
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
def query(tree, s, e, index, l, r):
if (l > e or r < s):
return -sys.maxsize -1
if (l <= s and r >= e):
return tree[index]
mid = (s + e) // 2
left = query(tree, s, mid,2 * index + 1, l, r)
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
def updateArray(arr, K):
global MAXN
# To store the segment tree
tree = [0 for i in range(MAXN)]
N = len(arr)
buildTree(arr, tree, 0, N - 1, 0)
for i in range(N):
# For 0th index only find
# the maximum out of 1 to i+K
if (i == 0):
print(query(tree, 0, N - 1, 0, 1, min(i + K, N - 1)),end = ' ')
continue
# For (N-1)th index only find
# the maximum out of 0 to (N-2)
if (i == N - 1):
print(query(tree, 0, N - 1, 0, max(0, i - K), N - 2))
continue
# Maximum from (i-K) to (i-1)
left = query(tree, 0, N - 1, 0, max(i - K, 0), i - 1)
# Maximum from (i+1) to (i+K)
right = query(tree, 0, N - 1, 0, i + 1, min(i + K, N - 1))
print(max(left, right),end = ' ')
# Driver Code
arr = [12, 5, 3, 9, 21, 36, 17]
K = 2
updateArray(arr, K)
# This code is contributed by shinjanpatra