Min and max values

Algorithm in php to find minimum and maximum values of an array using single loop

Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.

For example, arr=[1,3,5,7,9] . Our minimum sum is 1+3+5+7 and our maximum sum is 3+5+7+9. We would print 16 24



Concept: Initially, we should sort an array. To find minimum values, add first four integers and to find maximum values add last four integers.

Solution

<?php
$arr=[2,6,4,5,5];
sort($arr);
$min=0;
$max=0;
$lenArr=count($arr);
$cntArrIndex=$lenArr-1;
for($i=0;$i<$lenArr;$i++) {
	if($i==0) {
		$min=$arr[$i];
	}
	else if($i==$cntArrIndex) {
		$max +=$arr[$i];
	}
	else {
		$min +=$arr[$i];
		$max +=$arr[$i];
	}
}
echo $min." ".$max;
?>
Name
Email
Comments
Back
Funding

We need your support to operate it properly. We have lots of ideas but less fund, so help us with your funding.

Contribute

Thoughts of the day

A perfection of means, and confusion of aims, seems to be our main problem

Albert Einstein
Sell your product online

Do you want to sell products online with no extra cost?

Send your details, our executive will contact you

Email:

Mobile:

Location:

Polls
What you like most in facebook?
News
33%

 


Games
33%

 


Images
33%

 


Videos
1%

 


Tutorial On Request
Q. Ask us for any tutorial or any thing which helps to build your career better.
Email:
Query: