Given a non-empty array of integers, find the sum of the maximum value and the m
ID: 3881309 • Letter: G
Question
Given a non-empty array of integers, find the sum of the maximum value and the minimum value among all the elements of the array.
Write a function:
int solution(int A[], int N)
that accepts two parameters: an array A and its size N. The function should return the sum of the greatest and least elements of the array.
Input
6
10 15 4 19 2 12
Where,
The first line represents the size of the array.
The second line represents array elements.
Output
21
The maximum value is 19 and the minimum value is 2.
Assume that,
N is an integer within the range [1 to 10000].
Array elements are in the range [-10000 to 10000].
Program in Java
Explanation / Answer
/*
Program to find the sum of the greatest and least elements of the array.
*/
import java.util.Scanner;
class MinMaxExample {
public static void main(String args[])
{
int n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the no of integers you want to enter");
n=sc.nextInt(); /* size of an array */
int a[] = new int[n];
System.out.println("Enter the integers");
for(int i=0;i<n;i++)
a[i]=sc.nextInt(); /* input the no of elements in the array */
int res= solution(a,n); /* Calling the function solution */
System.out.println("The sum of maximum value and minimum value is "+ res);
}
// Method for getting the sum of maximum and minimum value in an array
public static int solution(int a[],int x)
{
int s=0;
int maxValue = a[0];
for(int i=1;i < a.length;i++)
{
if(a[i] > maxValue)
maxValue = a[i];
}
int minValue = a[0];
for(int i=1;i<a.length;i++)
{
if(a[i] < minValue)
minValue = a[i];
}
s=maxValue+ minValue;
return s;
}}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.