Algorithm

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

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;
?>