$arr = [1,2,3,4,5,6,98,65,190];
$max = $arr[0];
foreach($arr as $val){
while($val > $max){
$max = $val;
break;
}
}
max
без использования условных операторов:def max_(a, b):
return (a + b + abs(a-b)) / 2;
m = 0
arr = [1, 2, 3, 4, 5, 6, 98, 65, 190]
for val in arr:
m = max_(m, val)
print(m)
Min and max. Given an array of N elements, find the min and max using as few compares as possible. Brute force: find the max (N-1 compares), then find the min of the remaining elements (N-2 compares).
Solution 1. Divide and conquer: find min and max in each half (2T(N/2) compares), return min of 2 and max of 2 (2 compares). T(1) = 0, T(2) = 1, T(N) = 2T(N/2) + 2. Recurrence solution: T(N) = ceil(3N/2) - 2.
Solution 2. Divide the elements into pairs and compare two elements in each pair. Put the smallest elements in A and the largest in B. If n is odd, put element n in both A and B. This requires floor(n/2) comparisons. Now directly compute the minimum in A (ceil(n/2) - 1 comparisons) and the maximum in B (ceil(N/2) - 1) comparisons. [In fact, this is best possible.]