Articles

Find maximum of all subarrays of size k in Python

Find maximum of all subarrays of size k in Python


In this python programming article, we are going to learn

  • program to find maximum of all subarrays of size k in python

Program to find maximum of all subarrays of size k in Python

The program to find maximum of all subarrays of size k is as follows:

 

# Owner : TutorialsInhand Author : Devjeet Roy

def MaxSubArray(arr, n, k):
    max = 0  
    for i in range(n - k + 1):
        max = arr[i]
        for j in range(1, k):
            if arr[i + j] > max:
                max = arr[i + j]
        print(max, end = " ")
                

if __name__ == "__main__":
    array = list()
    n = int(input("Enter the size of the array: "))
    for i in range(n):
        array.append(int(input()))
    k = int(input("Enter the window size: "))
    MaxSubArray(array,n,k)

The output of find maximum of all subarrays of size k is as follows:

 

PS C:\Users\DEVJEET\Desktop\tutorialsInHand> python code.py
Enter the size of the array: 9
1
2
3
1
4
5
2
3
6
Enter the window size: 3
3 3 4 5 5 5 6

Few important tips about the program

1. The idea of the program is very simple. There will be a nested loop. The outer loop will marks the starting position of the index and the inner loop will run from the starting index to the value index+k, where k is the size of the subarray. Then the maximum is determined for that subarray and is printed.

2. The time complexity is O(n * k).

3. The space complexity is O(1).

 

maximum of all subarrays of size k in python code:

maximum of all subarrays of size k

 


Basic Python Programs
Python Conversion Programs

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Devjeet Roy
Full Stack Web Developer & Blockchain Enthusiast
Page Views :    Published Date : Apr 27,2021  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!