Monday, 4 February 2019

Minimum in SubArrays

Minimum in Sub Arrays


You are given an array A[] of size N and an integer K.
Your task is to print the Minimum element for each subarray of size 'k'.
In other words, for Each Valid Index i (1 <= i <= N - K)
You have to print min(A[i], A[i + 1], A[i + 2] .... A[i + k]).

Input Format
The First line will contain two Integers N and K.
The Second Line will contain N Integers denoting the elements of Array A[].

Constraints
1 <= N <= 10^5
1 <= K <= N
1 <= A[i] <= 10^6

Output Format
Print the Minimum elements for each subarray of Size K separated by space.


Sample TestCase 1

Input
5 2
10 0 3 2 5

Output
0 0 2 2

Code:

using System;
using System.Linq;

namespace ConsoleApp
{
    internal class DonNetTest
    {
        private static void Main(string[] args)
        {
            string inputFirstLine = System.Console.ReadLine();
            string[] firstLine_arr = inputFirstLine.Split(' ').ToArray();

            int n = Int32.Parse(firstLine_arr[0]);
            int k = Int32.Parse(firstLine_arr[1]);

            int[] arr = new int[k];

            string inputSecondLine = System.Console.ReadLine();
            string[] secondLine_arr = inputSecondLine.Split(' ').ToArray();
            arr = Array.ConvertAll(secondLine_arr, Int32.Parse);

            printMinimumArray(n, k, arr);
        }

        private static void printMinimumArray(int n, int k, int[] arr)
        {
            int j, min;

            for (int i = 0; i <= n - k; i++)
            {
                min = arr[i];

                for (j = 1; j < k; j++)
                {
                    if (arr[i + j] < min )
                        min = arr[i + j];
                }
                Console.Write(min + " ");
            }
        }
    }
}



No comments:

Post a Comment

Factorial of a Number

Recently Viewed