We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Post 56
Hacker Rank 27 - Mangoes
Published on: 2025-08-04
Tags:
elixir, Side Project, Hacker Rank
For this task we want to find out the how many friends we can invite to a mango party. Its a very weird set of issues what we need to deal with as people will have a hunger and a happiness index... Yeah I know its weird but lets keep going.
Okay so the rule for the amount of mangoes that a friend will need is this.
hunger + (number_of_friends - 1 * happiness_index)
So yes the happiness index can have a large part of the total mangoes needed, but a low happiness index and a large hunger makes it so we can't just use that.
So I came up with an idea that we can choose a random k (number of friends invited) and then testing the different friends values. Once you have all the values for the friends you can sort the list and pick the first k friends.
def can_invite?(friends, k, mango_limit) do
friends
|> Enum.map(fn {hunger, happiness} -> hunger + (k - 1) * happiness end)
|> Enum.sort()
|> Enum.take(k)
|> Enum.sum()
|> Kernel.<= (mango_limit)
end
This is a great way to test any value of k, but how to pick your k. Well that is where a BTS will come in the basic Idea is that you have the max (number of friends) min (0 no friend invites), and choose a middle value and see if it works.
If it works then try a higher value (now the mid of the end and the middle value from the last step) repeat till you get to the end or you get no values that work).
def binary_search(low, high, friends, mango_limit) do
do_search(low, high, friends, mango_limit)
end
defp do_search(low, high, _friends, _mango_limit) when low > high, do: high
defp do_search(low, high, friends, mango_limit) do
mid = div(low + high, 2)
if can_invite?(friends, mid, mango_limit) do
do_search(mid + 1, high, friends, mango_limit)
else
do_search(low, mid - 1, friends, mango_limit)
end
end