Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Maximum of all subarrays of size K using Segment Tree
Next article icon

Maximum of all subarrays of size K using Segment Tree

Last Updated : 28 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] and an integer K, the task is to find the maximum for each and every contiguous subarray of size K.

Examples: 

Input: arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}, K = 3 
Output: 3 3 4 5 5 5 6 
Explanation: 
Maximum of 1, 2, 3 is 3 
Maximum of 2, 3, 1 is 3 
Maximum of 3, 1, 4 is 4 
Maximum of 1, 4, 5 is 5 
Maximum of 4, 5, 2 is 5 
Maximum of 5, 2, 3 is 5 
Maximum of 2, 3, 6 is 6

Input: arr[] = {8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, K = 4 
Output: 10 10 10 15 15 90 90 
Explanation: 
Maximum of first 4 elements is 10, similarly for next 4 
elements (i.e from index 1 to 4) is 10, So the sequence 
generated is 10 10 10 15 15 90 90 

Approach: 
The idea is to use the Segment tree to answer the maximum of all subarrays of size K.

  1. Representation of Segment trees 
    • Leaf Nodes are the elements of the input array.
    • Each internal node represents the maximum of all of its children.
  2. Construction of Segment Tree from the given array: 
    • We start with a segment arr[0 . . . n-1], and every time we divide the current segment into two halves(if it has not yet become a segment of length 1), and then call the same procedure on both halves, and for each such segment, we store the maximum value in a segment tree node.
    • All levels of the constructed segment tree will be completely filled except the last level. Also, the tree will be a full Binary Tree because we always divide segments into two halves at every level.
    • Since the constructed tree is always a full binary tree with n leaves, there will be n - 1 internal nodes. So total nodes will be 2 * n – 1.
    • The height of the segment tree will be log2n.
    • Since the tree is represented using an array and the relation between parent and child indexes must be maintained, the size of memory allocated for the segment tree will be 2 *(2ceil(log2n))-1.

Below is the implementation of the above approach. 

C++
// C++  program to answer Maximum // of allsubarrays of size k // using segment tree #include <bits/stdc++.h> using namespace std;  #define MAX 1000000  // Size of segment // tree = 2^{log(MAX)+1} int st[3 * MAX];  // A utility function to get the // middle index of given range. int getMid(int s, int 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 void constructST(int node, int s,                  int e, int 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     int 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  */ int getMax(int node, int s,            int e, int l,            int r) {     // If segment of this node     // does not belong to     // given range     if (s > r || e < l)         return INT_MIN;      // If segment of this node     // is completely part of     // given range, then return     // the max of segment     if (s >= l && e <= r)         return st[node];      // If segment of this node     // is partially the part     // of given range     int 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 void printKMax(int n, int k) {     for (int i = 0; i < n; i++) {         if ((k - 1 + i) < n)             cout << getMax(1, 0, n - 1,                            i, k - 1 + i)                  << " ";         else             break;     } }  // Driver code int main() {     int k = 4;     int arr[] = { 8, 5, 10, 7, 9, 4, 15,                   12, 90, 13 };     int n = sizeof(arr) / sizeof(arr[0]);      // Function to construct the     // segment tree     constructST(1, 0, n - 1, arr);      printKMax(n, k);      return 0; } 
Java
// Java program to answer Maximum // of allsubarrays of size k // using segment tree import java.io.*; import java.util.*;  class GFG{  static int MAX = 1000000;  // Size of segment // tree = 2^{log(MAX)+1} static int[] st = new int[3 * MAX];  // A utility function to get the // middle index of given range. static int getMid(int s, int 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 static void constructST(int node, int s,                         int e, int[] 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     int mid = getMid(s, e);      constructST(2 * node, s, mid, arr);     constructST(2 * node + 1,                  mid + 1, e, arr);          st[node] = Math.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  */ static int getMax(int node, int s, int e,                             int l, int r) {          // If segment of this node     // does not belong to     // given range     if (s > r || e < l)         return Integer.MIN_VALUE;      // If segment of this node     // is completely part of     // given range, then return     // the max of segment     if (s >= l && e <= r)         return st[node];      // If segment of this node     // is partially the part     // of given range     int mid = getMid(s, e);      return Math.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 static void printKMax(int n, int k) {     for(int i = 0; i < n; i++)     {         if ((k - 1 + i) < n)             System.out.print(getMax(1, 0, n - 1,                                      i, k - 1 + i) + " ");         else             break;     } }  // Driver code public static void main(String[] args) {     int k = 4;     int[] arr = { 8, 5, 10, 7, 9,                    4, 15, 12, 90, 13 };     int n = arr.length;      // Function to construct the     // segment tree     constructST(1, 0, n - 1, arr);      printKMax(n, k); } }  // This code is contributed by akhilsaini 
Python3
# 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 
C#
// C# program to answer Maximum // of allsubarrays of size k // using segment tree using System;  class GFG{  static int MAX = 1000000;  // Size of segment // tree = 2^{log(MAX)+1} static int[] st = new int[3 * MAX];  // A utility function to get the // middle index of given range. static int getMid(int s, int 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 static void constructST(int node, int s,                          int e, int[] 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     int mid = getMid(s, e);      constructST(2 * node, s, mid, arr);     constructST(2 * node + 1, mid + 1, e, arr);          st[node] = Math.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  */ static int getMax(int node, int s, int e,                             int l, int r) {          // If segment of this node     // does not belong to     // given range     if (s > r || e < l)         return int.MinValue;      // If segment of this node     // is completely part of     // given range, then return     // the max of segment     if (s >= l && e <= r)         return st[node];      // If segment of this node     // is partially the part     // of given range     int mid = getMid(s, e);      return Math.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 static void printKMax(int n, int k) {     for(int i = 0; i < n; i++)     {         if ((k - 1 + i) < n)             Console.Write(getMax(1, 0, n - 1,                                   i, k - 1 + i) + " ");         else             break;     } }  // Driver code public static void Main() {     int k = 4;     int[] arr = { 8, 5, 10, 7, 9,                   4, 15, 12, 90, 13 };     int n = arr.Length;      // Function to construct the     // segment tree     constructST(1, 0, n - 1, arr);      printKMax(n, k); } }  // This code is contributed by akhilsaini 
JavaScript
<script>  // Javascript program to answer Maximum // of allsubarrays of size k // using segment tree  var MAX = 1000000;  // Size of segment // tree = 2^{log(MAX)+1} var st = Array(3*MAX);  // A utility function to get the // middle index of given range. function getMid(s, e) {     return s + parseInt((e - s) / 2); } // A recursive function that // constructs Segment Tree for // array[s...e]. node is index // of current node in segment // tree st function 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     var mid = getMid(s, e);      constructST(2 * node, s,                 mid, arr);     constructST(2 * node + 1,                 mid + 1, e,                 arr);     st[node] = Math.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  */ function getMax(node, s, e, l, r) {     // If segment of this node     // does not belong to     // given range     if (s > r || e < l)         return -1000000000;      // If segment of this node     // is completely part of     // given range, then return     // the max of segment     if (s >= l && e <= r)         return st[node];      // If segment of this node     // is partially the part     // of given range     var mid = getMid(s, e);      return Math.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 function printKMax(n, k) {     for (var i = 0; i < n; i++) {         if ((k - 1 + i) < n)             document.write( getMax(1, 0, n - 1,                            i, k - 1 + i)                  + " ");         else             break;     } }  // Driver code var k = 4; var arr = [8, 5, 10, 7, 9, 4, 15,               12, 90, 13]; var n = arr.length; // Function to construct the // segment tree constructST(1, 0, n - 1, arr); printKMax(n, k);   </script>  

Output: 
10 10 10 15 15 90 90

 

Time Complexity: O(N * log K)
Auxiliary Space: O(N * log K) 


Related Article: Sliding Window Maximum (Maximum of all subarrays of size k)
 Related Topic: Segment Tree


Next Article
Maximum of all subarrays of size K using Segment Tree

S

saurabhshadow
Improve
Article Tags :
  • Tree
  • Algorithms
  • Competitive Programming
  • DSA
  • Arrays
  • Segment-Tree
  • subarray
Practice Tags :
  • Algorithms
  • Arrays
  • Segment-Tree
  • Tree

Similar Reads

    Segment Tree
    Segment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
    3 min read
    Segment tree meaning in DSA
    A segment tree is a data structure used to effectively query and update ranges of array members. It's typically implemented as a binary tree, with each node representing a segment or range of array elements. Segment tree Characteristics of Segment Tree:A segment tree is a binary tree with a leaf nod
    2 min read
    Introduction to Segment Trees - Data Structure and Algorithm Tutorials
    A Segment Tree is used to store information about array intervals in its nodes.It allows efficient range queries over array intervals.Along with queries, it allows efficient updates of array items.For example, we can perform a range summation of an array between the range L to R in O(Log n) while al
    15+ min read
    Persistent Segment Tree | Set 1 (Introduction)
    Prerequisite : Segment Tree Persistency in Data Structure Segment Tree is itself a great data structure that comes into play in many cases. In this post we will introduce the concept of Persistency in this data structure. Persistency, simply means to retain the changes. But obviously, retaining the
    15+ min read
    Segment tree | Efficient implementation
    Let us consider the following problem to understand Segment Trees without recursion.We have an array arr[0 . . . n-1]. We should be able to, Find the sum of elements from index l to r where 0 <= l <= r <= n-1Change the value of a specified element of the array to a new value x. We need to d
    12 min read
    Iterative Segment Tree (Range Maximum Query with Node Update)
    Given an array arr[0 . . . n-1]. The task is to perform the following operation: Find the maximum of elements from index l to r where 0 <= l <= r <= n-1.Change value of a specified element of the array to a new value x. Given i and x, change A[i] to x, 0 <= i <= n-1. Examples: Input:
    14 min read
    Range Sum and Update in Array : Segment Tree using Stack
    Given an array arr[] of N integers. The task is to do the following operations: Add a value X to all the element from index A to B where 0 ? A ? B ? N-1.Find the sum of the element from index L to R where 0 ? L ? R ? N-1 before and after the update given to the array above.Example: Input: arr[] = {1
    15+ min read
    Dynamic Segment Trees : Online Queries for Range Sum with Point Updates
    Prerequisites: Segment TreeGiven a number N which represents the size of the array initialized to 0 and Q queries to process where there are two types of queries: 1 P V: Put the value V at position P.2 L R: Output the sum of values from L to R. The task is to answer these queries. Constraints: 1 ? N
    15+ min read
    Applications, Advantages and Disadvantages of Segment Tree
    First, let us understand why we need it prior to landing on the introduction so as to get why this concept was introduced. Suppose we are given an array and we need to find out the subarray Purpose of Segment Trees: A segment tree is a data structure that deals with a range of queries over an array.
    4 min read

    Lazy Propagation

    Lazy Propagation in Segment Tree
    Segment tree is introduced in previous post with an example of range sum problem. We have used the same "Sum of given Range" problem to explain Lazy propagation   How does update work in Simple Segment Tree? In the previous post, update function was called to update only a single value in array. Ple
    15+ min read
    Lazy Propagation in Segment Tree | Set 2
    Given an array arr[] of size N. There are two types of operations: Update(l, r, x) : Increment the a[i] (l <= i <= r) with value x.Query(l, r) : Find the maximum value in the array in a range l to r (both are included).Examples: Input: arr[] = {1, 2, 3, 4, 5} Update(0, 3, 4) Query(1, 4) Output
    15+ min read
    Flipping Sign Problem | Lazy Propagation Segment Tree
    Given an array of size N. There can be multiple queries of the following types. update(l, r) : On update, flip( multiply a[i] by -1) the value of a[i] where l <= i <= r . In simple terms, change the sign of a[i] for the given range.query(l, r): On query, print the sum of the array in given ran
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences