# Python3 program to answer maximum # of all subarrays of size k # using segment tree import sys MAX = 1000000 # Size of segment # tree = 2^{log(MAX)+1} st = [0] * (3 * MAX) # A utility function to get the # middle index of given range. def getMid(s, e): return s + (e - s) // 2 # A recursive function that # constructs Segment Tree for # array[s...e]. node is index # of current node in segment # tree st def constructST(node, s, e, arr): # If there is one element in # array, store it in current # node of segment tree and return if (s == e): st[node] = arr[s] return # If there are more than # one elements, then recur # for left and right subtrees # and store the max of # values in this node mid = getMid(s, e) constructST(2 * node, s, mid, arr) constructST(2 * node + 1, mid + 1, e, arr) st[node] = max(st[2 * node], st[2 * node + 1]) ''' A recursive function to get the maximum of range[l, r] The following parameters for this function: st -> Pointer to segment tree node -> Index of current node in the segment tree . s & e -> Starting and ending indexes of the segment represented by current node, i.e., st[node] l & r -> Starting and ending indexes of range query ''' def getMax(node, s, e, l, r): # If segment of this node # does not belong to # given range if (s > r or e < l): return (-sys.maxsize - 1) # If segment of this node # is completely part of # given range, then return # the max of segment if (s >= l and e <= r): return st[node] # If segment of this node # is partially the part # of given range mid = getMid(s, e) return max(getMax(2 * node, s, mid, l, r), getMax(2 * node + 1, mid + 1, e, l, r)) # Function to print the max # of all subarrays of size k def printKMax(n, k): for i in range(n): if ((k - 1 + i) < n): print(getMax(1, 0, n - 1, i, k - 1 + i), end = " ") else: break # Driver code if __name__ == "__main__": k = 4 arr = [ 8, 5, 10, 7, 9, 4, 15, 12, 90, 13 ] n = len(arr) # Function to construct the # segment tree constructST(1, 0, n - 1, arr) printKMax(n, k) # This code is contributed by chitranayal