Last Updated on March 28, 2022 by Ria Pathak
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:
- Initialize variables
max_e
,min_e
asINT_MIN
andINT_MAX
respectively.- Traverse the array, if the value of current element is greater than
max_e
, update value ofmax_e
to the current element’s value. Similarly, if the value of current element is less thanmin_e
, update it too.- Keep updating variables
max_e
andmin_e
.- Post array traversal, we will get our Max and Min elements.
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--; } } }
[forminator_quiz id="632"]
Space Complexity: O(1)
This article tried to discuss Basic Mathematics. Hope this blog helps you understand and solve the problem. To practice more problems on Basic Mathematics you can check out MYCODE | Competitive Programming.