Sunday, August 1, 2021

find min max

 Given an array A of size N of integers. Your task is to find the minimum and maximum elements in the array.

 

Answer:

#include <stdio.h>


struct pair {

    long long int min;

    long long int max;

};


struct pair getMinMax(long long int arr[], long long int n) ;


int main() {

    long long int t, n, a[100002], i;

    struct pair minmax;


    scanf("%lld", &t);

    while (t--) {

        scanf("%lld", &n);


        for (i = 0; i < n; i++) scanf("%lld", &a[i]);

        minmax = getMinMax(a, n);

        printf("%lld %lld\n", minmax.min, minmax.max);

    }

    return 0;

}// } Driver Code Ends



// User function Template for C


struct pair getMinMax(long long int arr[], long long int n) {

    struct pair minmax;

    if(n==1)  //if size of array is 1 them min and max will be same

    {

        minmax.min=arr[0];

        minmax.max=arr[0];

        

        return minmax;

    }

    //if more than one element present

    

    if(arr[0]>arr[1])

    {

        minmax.max=arr[0];

        minmax.min=arr[1];

    }

    else

    {

        minmax.max=arr[1];

        minmax.min=arr[0];

    }

    

    

    for(int i=2;i<n;i++)

    {

        if(arr[i]>minmax.max)

        {

            minmax.max=arr[i];

        }

    }

    for(int i=2;i<n;i++)

    {

        if(arr[i]<minmax.min)

        {

            minmax.min=arr[i];

        }

    }

    

    return minmax;

    //printf("%d",min);

    //printf("%d",max);


    

}

No comments:

Post a Comment

Java Regex

You are updating the username policy on your company's internal networking platform. According to the policy, a username is considered v...