C Program to find the maximum for each and every contiguous subarray of size k from an array

Write a program to find the maximum for each and every contiguous subarray of size k from a given array.

For example:

The given array is:
5 8 2 3 1 6 8 5 23 26
The length of each subarray is: 4
The contigious subarray of length 4 and their maximum value are:
5 8 2 3 -> 8
8 2 3 1 -> 8
2 3 1 6 -> 6
3 1 6 8 -> 8
1 6 8 5 -> 8
6 8 5 23 -> 23
8 5 23 26 -> 26

 Input Format:
The first line of the input has the size of the array.
The second line has the elements of the array.
The third line has the length of the subarray to be formed

Sample Input 1

10
5 8 2 3 1 6 8 5 23 26
4

Sample Output 1

5 8 2 3 -> 8
8 2 3 1 -> 8
2 3 1 6 -> 6
3 1 6 8 -> 8
1 6 8 5 -> 8
6 8 5 23 -> 23
8 5 23 26 -> 26

Code:

#include<stdio.h>

int main()
{
    int n;
    scanf("%d",&n);
    int a[100];
    for(int i=0;i<n;i++) scanf("%d",&a[i]);
    int k;
    scanf("%d",&k);
    int b[50];

    for(int i=0;i<n;i++)
    {
        int su =a[i];
        if((n-i) < k) break;
        int l=0;
        for(int j =i;j<n;j++)
        {
            if(l == 4) break;

            if(su < a[j]) su =a[j];
            printf("%d ",a[j]);
            l++;

        }
        printf("-> %d\n",su);

    }
}
Code language: C/AL (cal)

Leave a Comment