Maximum of all subarrays of size k | Practice | GeeksforGeeks

Given an array arr[] of size N and an integer K. Find the maximum for each and every contiguous subarray of size K.
Example 1:
Input:
N = 9, K = 3
arr[] = 1 2 3 1 4 5 2 3 6
Output: 
3 3 4 5 5 5 6 
Explanation: 
1st contiguous subarray = {1 2 3} Max = 3
2nd contiguous subarray = {2 3 1} Max = 3
3rd contiguous subarray = {3 1 4} Max = 4
4th contiguous subarray = {1 4 5} Max = 5
5th contiguous subarray = {4 5 2} Max = 5
6th contiguous subarray = {5 2 3} Max = 5
7th contiguous subarray = {2 3 6} Max = 6
Example 2:
Input:
N = 10, K = 4
arr[] = 8 5 10 7 9 4 15 12 90 13
Output: 
10 10 10 15 15 90 90
Explanation: 
1st contiguous subarray = {8 5 10 7}, Max = 10
2nd contiguous subarray = {5 10 7 9}, Max = 10
3rd contiguous subarray = {10 7 9 4}, Max = 10
4th contiguous subarray = {7 9 4 15}, Max = 15
5th contiguous subarray = {9 4 15 12}, 
Max = 15
6th contiguous subarray = {4 15 12 90},
Max = 90
7th contiguous subarray = {15 12 90 13}, 
Max = 90

Your Task:  
You dont need to read input or print anything. Complete the function max_of_subarrays() which takes the array, N and K as input parameters and returns a list of integers denoting the maximum of every contiguous subarray of size K.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(k)
Constraints:
1 ≤ N ≤ 107
1 ≤ K ≤ N
0 ≤ arr[i] ≤ 107
0
amanahirwar1512 days ago
C++ EASY SOLUTION USING DEQUE
vector <int> max_of_subarrays(int *arr, int n, int k)   {       vector<int> ans;       deque<int> dq(k);       int i;       for(i=0; i<k; ++i){           while((!dq.empty()) && arr[i]>=arr[dq.back()]){               dq.pop_back();           }           dq.push_back(i);       }       ans.push_back(arr[dq.front()]);       for(i=k; i<n; ++i){           if(dq.front()==i-k){               dq.pop_front();           }                      while((!dq.empty()) && arr[i]>=arr[dq.back()]){               dq.pop_back();           }           dq.push_back(i);           ans.push_back(arr[dq.front()]);       }       return ans;   }
+1
bhaskarmaheshwari83 days ago
vector<int> ans;          int i=0,j=0;          int max1=INT_MIN;          while(j<n)          {              if(j-i+1<=k)              {                  max1=max(max1,arr[j]);                  if(j-i+1==k)                  {                      ans.push_back(max1);                  }                  j++;                                }              else              {                  if(arr[i]==max1)                  {                   max1=INT_MIN;                  for(int l=i+1;l<=i+k-1;l++)                  {                      max1=max(max1,arr[l]);                  }                                    }                  i++;                                                  }          }          return ans; 
0
kknamish3 days ago
class Solution:
    def max_of_subarrays(self,arr,n,k):
        i,j=0,0
        mx=max(arr[:k])
        ans=[mx]
        for i in range(k,n):
            if mx!=arr[i-k]:
                mx=max(mx,arr[i])
            else:
                mx=max(arr[i-k+1:i+1])
            ans.append(mx)
        return ans
+1
harendraseervi1234567895 days ago
Easy C++ solution
vector <int> max_of_subarrays(int *arr, int n, int k)
   {
       
       // your code here
       vector<int>ans;
       int maxi=INT_MIN;
       for(int i=0;i<k;i++){
           if(arr[i]>maxi) maxi=arr[i];
       }
       ans.push_back(maxi);
       for(int i=k;i<n;i++){
           if(arr[i]>maxi){
               ans.push_back(arr[i]);
               maxi=arr[i];
           }
           else{
               if(arr[i-k]!=maxi){
                   ans.push_back(maxi);
               }
               else{
                   maxi=INT_MIN;
                   for(int j=i-k+1;j<=i;j++){
                       maxi=max(arr[j],maxi);
                   }
                   ans.push_back(maxi);
               }
           }
       }
       return ans;
   }
0
tarunkanade5 days ago
4.6/6.8
static ArrayList <Integer> max_of_subarrays(int arr[], int n, int k)
    {
        // Your code here
        ArrayDeque<Integer> q = new ArrayDeque<>();
        ArrayList<Integer> maxSub = new ArrayList<>();
        
        for(int i=0; i<k; i++){
            while(!q.isEmpty() && arr[i] >= arr[q.peekLast()]){
                q.pollLast();
            }
            q.offerLast(i);
        }
        
        for(int i=k; i<n; i++){
            maxSub.add(arr[q.peekFirst()]);
            
            while(!q.isEmpty() && q.peekFirst() <= i-k){
                q.pollFirst();
            }
            
            while(!q.isEmpty() && arr[i] >= arr[q.peekLast()]){
                q.pollLast();
            }
            
            q.offerLast(i);
        }
        
        maxSub.add(arr[q.peekFirst()]);
        
        return maxSub;
    }
+1
soumik20001 week ago
Java Max Heap Simple solution
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(Collections.reverseOrder());       ArrayList<Integer> list = new ArrayList<>();       for(int i = 0; i<k; i++)       {           pq.add(arr[i]);       }       list.add(pq.peek());       for(int i = k; i<n; i++)       {           pq.remove(arr[i-k]);           pq.add(arr[i]);           list.add(pq.peek());       }              return list;
0
himanshukug19cs2 weeks ago
java 
 int[] maxf= new int[n];        Stack<Integer> st = new Stack<>();       for(int i=n-1;i>=0;i--){           while(!st.empty()&&arr[st.peek()]<=arr[i]){               st.pop();           }           if(st.empty())                maxf[i]=n;           else                 maxf[i]=st.peek();           st.push(i);             }       ArrayList <Integer> al = new ArrayList<>();             for(int i=0;i<=n-k;i++){           int j=i;           while(maxf[j]<i+k){               j=maxf[j];           }           if(j==i)               al.add(arr[i]);           else               al.add(arr[j]);       }       return al;   }
-3
1941012837shivamkumarsharma3 weeks ago
JAVA Simple Code
// by 1941012837_Shivam Kumar Sharma_ITER(SOA)
class Solution
{
    //Function to find maximum of each subarray of size k.
    static ArrayList <Integer> max_of_subarrays(int arr[], int n, int k)
    {
        int len=n-k;
        int max=0;
        ArrayList<Integer>list= new ArrayList<>();
        
        for(int i=0;i<=len;i++){
            max=arr[i];
            
            for(int j=1;j<k;j++){
            	max=Math.max(arr[i+j],max);
             }   
            list.add(max);
       }	return (list);
      		}	
      			}
+1
anupb4 weeks ago
Python Solution
 
class Solution:
    
    #Function to find maximum of each subarray of size k.
    def max_of_subarrays(self,arr,n,k):
        result = list()
        max_num = 0
        first_pointer = 0
        
        if k > n:
            return max(arr)
        
        sub_array = arr[0:k]
        max_num = max(sub_array)
        result.append(max_num)
        
        for i in range(k,n):
            # for optimization
            if max_num > arr[first_pointer]:
                sub_array.pop(0)
                sub_array.append(arr[i])
                max_num = max(max_num, arr[i])
                result.append(max_num)
                first_pointer += 1
            else:
                sub_array.pop(0)
                sub_array.append(arr[i])
                max_num = max(sub_array)
                result.append(max_num)
                first_pointer += 1
        
        return result
 
+1
inukurthibhargavi2384 weeks ago
def max_of_subarrays(self,arr,n,k):
       ans=[]
       i=k
       j=0
       ans.append(max(arr[:k]))
       while i<n:
           if arr[j]==ans[-1]:
               ans.append(max(arr[j+1:i+1]))
           elif arr[i]>ans[-1]:
               ans.append(arr[i])
           else:
               ans.append(ans[-1])
           j+=1
           i+=1
      
       return ans
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.