If we need to find the maximum (minimum) not among all elements of the array, but only among numbers that satisfy a certain condition, then we must take into account the fact that the first element that we take as the initial value of the maximum (minimum) will not always satisfy our requirements.
For example, if we look for the maximum negative number, then having the data set: {5, -2, 4, 2, -1, -3} we will get the number 5 in the initial value of the maximum, and it is positive and more than any negative. And therefore, the condition X> maximum will always be false.
Therefore, it is not enough to add only a check for a negative number in the algorithm from the previous task, it is also necessary to take into account the fact that the first number may not satisfy the required condition (in this case, be negative)
You can fix this by adding the following condition inside the loop:
pseudocode:
if X is negative, then
if maximum> = 0 or maximum <X, then
maximum = X
In the indicated code, the condition maximum> = 0 allows the action maximum = A to be performed even if initially a value that obviously exceeds the others gets into the variable maximum (in the example considered by us, the value is 5).
We also note that if the range of variation of numbers is known, then as the initial value of the maximum (minimum), you can take the minimum (maximum) number from the specified range.