Suppose we have a list of scores for different number of participants. We have to find the runner-up score.
So, if the input is like scores = [5,8,2,6,8,5,8,7], then the output will be 7 because the winner score is 8 and second largest score is 7.
To solve this, we will follow these steps −
- winner := -99999
- runner_up := -99999
- for each i in scores, do
- if i > winner, then
- winner := i
- runner_up := winner
- otherwise when i < winner and i > runner_up, then
- runner_up := i
- if i > winner, then
- return runner_up
Example
Let us see the following implementation to get better understanding
def solve(scores): winner = -99999 runner_up = -99999 for i in scores: if (i > winner): winner, runner_up = i, winner elif (i < winner and i > runner_up): runner_up = i return runner_up scores = [5,8,2,6,8,5,8,7] print(solve(scores))
Input
[5,8,2,6,8,5,8,7]
Output
7