Task: Given N numbers. Find the second largest maximum element of the sequence..
This task has two interpretations.
For example, if we are given a set of numbers: 10 15 20 35 14 35 10, then what should be the answer?
By "second largest maximum element" or simply "second maximum", we can understand:
1) the value that would have stood in the penultimate place if we had all the values ??arranged (sorted) in non-decreasing order (each next one is greater than or equal to the previous one). Then for the considered set of numbers the answer will be the value 35
2) the value of the element, of which only the maximum is greater. Then the answer is 20
If there is only one maximum element in the set of numbers (all the others are smaller), then both interpretations coincide, and the answer will be the same for both cases, otherwise the answer will be different.
Consider the first case (the algorithm will be written in pseudocode).
To find the answer, we will use two variables:
1) maximum1
- maximum value (first maximum)
2) maximum2
- second maximum (our answer)
If the range of variation of the values is known, then as the initial values we take a number that is obviously less than the lower boundary of the range (for example, for a range from -1000 to 1000 - take the number -1001)
If the range of values is unknown, then the first two input numbers can be written in the initial values of the variables maximum 1 and maximum 2, and then compare these two variables
input N //amount of numbers
input a, b
maximum1 = а
maximum2 = b
if b > a then
maximum1 = b
maximum2 = a
Next, we consider all the other elements (the first 2 have already been viewed, so we will start from the 3rd)
for i <-- 3 to n
input а
if а > maximum1 //a value greater than the maximum1
then
maximum2 = maximum1 //the former first high will become the second
maximum1 = а //the first high will be a new element
else
// next element no more than maximum1
// it must be compared with a value of maximum 2
if а > maximum2 then
maximum2 = а // accept it as a new value maximum 2
// maximum1 in this case does not change
Try to implement this algorithm yourself