34.4k views
1 vote
Define a function max_n(arr, n) that takes in an array and an integer as arguments. Your function will then return the n largest values from that array as an array containing n elements. It is safe to assume that arr will have at least n elements. The resulting array should have the largest number on the end and the smallest number at the beginning.

User Shmack
by
4.1k points

1 Answer

3 votes

Answer:

def max_n(arr, n):

arr.sort()

i = len(arr)-n

return arr[i:]

Step-by-step explanation:

Define a function called max_n that takes two parameters, an array and an integer

Sort the array

In order to get the last n largest values, we need to slice the array. To do that we need a starting point. Our starting point of slicing will be the "lentgh of the array - n". That means, if we start slicing from that index to the last in the sorted array, we will get the last n largest values.

Assume array is 10, 2, 444, 91 initially.

When we sort it, it becomes 2, 10, 91, 444

Now let's say we want last 2 largest values, our sliced array index should start from 2 and go until the end

i = 4 - 2 = 2 → arr[2:] will return us 91 and 444

User Footy
by
5.0k points