CONCEPTS USED:

Basic Mathematics

DIFFICULTY LEVEL:

Easy

PROBLEM STATEMENT(SIMPLIFIED):

With a given array of size N, find the largest (maximum) and smallest (minimum) element from the elements.

See original problem statement here

For Example :

N = 5 
Arr[] = [4, 3, 2, 1, 5]

Maximum element = 5
Minimum element = 1

SOLVING APPROACH:

  1. Initialize variables max_e, min_e as INT_MIN and INT_MAX respectively.

  2. Traverse the array, if the value of current element is greater than max_e, update value of max_e to the current element's value. Similarly, if the value of current element is less than min_e, update it too.

  3. Keep updating variables max_e and min_e.

  4. Post array traversal by referring programming languages online course.

NOTE:

INT_MAX is a macro that specifies that an integer variable cannot store any value beyond this limit.

INT_MIN specifies that an integer variable cannot store any value below this limit.

SOLUTIONS:

#include<stdio.h>
#include<limits.h>

void main()
{
  int t;
  scanf("%d",&t);
  while(t--)
  {
    int n;
    scanf("%d",&n);
    int arr[n];
    int max_e = INT_MIN;
    int min_e = INT_MAX;
    for(int i=0;i<n;i++)
    {
      scanf("%d",&arr[i]);
      if(arr[i]>max_e)
        max_e = arr[i];
      if(arr[i]<min_e)
        min_e = arr[i];
    }
    printf("%d %d\n",max_e,min_e);
  }
}
#include <bits/stdc++.h>
using namespace std;

int main()
{
  int t;cin>>t;
  while(t--)
  {
    int n;cin>>n;
    int arr[n];
    int max_e = INT_MIN;
    int min_e = INT_MAX;
    for(int i=0;i<n;i++)
    {
      cin>>arr[i];
      if(arr[i]>max_e)
        max_e = arr[i];
      if(arr[i]<min_e)
        min_e = arr[i];
    }
    cout<<min_e<<" "<<max_e<<"\n";   
  }
  return 0;
}


import java.util.*;
import java.io.*;

public class Main
{
  public static void main(String args[]) throws IOException 
  {
    Scanner sc = new Scanner(System.in);
    int t;
    t = sc.nextInt();
    while(t!=0)
    {
      int n;
      n = sc.nextInt();
      int arr[] = new int[n];
      int max_e = Integer.MIN_VALUE;
      int min_e = Integer.MAX_VALUE;
      for(int i=0;i<n;i++)
      {
        arr[i] = sc.nextInt();
        if(arr[i]>max_e)
          max_e = arr[i];
        if(arr[i]<min_e)
          min_e = arr[i];

      }
      System.out.println(min_e + " " + max_e);
      t--;
    }
  }  
}


Space Complexity: O(1)
Previous post Array Rotation
Next post Print the Pattern

Leave a Reply

Your email address will not be published. Required fields are marked *