|
| 1 | + |
| 2 | + |
| 3 | +""" |
| 4 | +Write a function that takes in an array of at least three integers and, |
| 5 | +without sorting the input array, returns a sorted array of the three largest |
| 6 | +integers in the input array. |
| 7 | +
|
| 8 | +# Approach |
| 9 | +
|
| 10 | +- We will use three variables to store the three max values and initialize them with int_minimum |
| 11 | +- We will iterate through the array and compare the values with the three variables |
| 12 | +- If the value is greater than the first variable, we will update the variables |
| 13 | +- If the value is greater than the second variable, we will update the variables |
| 14 | +- If the value is greater than the third variable, we will update the variables |
| 15 | +- Return the three variables as a sorted array |
| 16 | +
|
| 17 | +""" |
| 18 | + |
| 19 | + |
| 20 | + |
| 21 | +def three_max_no(arr:list)-> list: |
| 22 | + # give int minvalue to a,b, |
| 23 | + max_1,max_2,max_3= -9999,-9999,-9999 |
| 24 | + # we will iterate through the array and compare the values |
| 25 | + for i in arr: |
| 26 | + if i > max_1: |
| 27 | + # if the value is greater than the first variable, we will update the variables |
| 28 | + max_1,max_2,max_3 = i, max_1, max_2 |
| 29 | + elif i > max_2: |
| 30 | + # if the value is greater than the second variable, we will update the variables |
| 31 | + max_2, max_3 = i, max_2 |
| 32 | + elif i > max_3: |
| 33 | + # if the value is greater than the third variable, we will update the variables |
| 34 | + max_3 = i |
| 35 | + # return the three max values as a sorted array |
| 36 | + return [max_1, max_2, max_3] |
| 37 | + |
| 38 | + |
| 39 | +# example-1 |
| 40 | +arr=[141,1,17,-7,-17,-27,18,541,8,7,7] |
| 41 | +print(three_max_no(arr)) |
| 42 | + |
| 43 | +# sample output [541, 141, 18] |
0 commit comments