The first principle of debugging Mathematica (or even just writing new code): write and test small pieces first! Don't write a complex piece of code like what you are showing and then wonder why it doesn't do what you think it should be doing. Build it up pice by piece, testing each piece in turn. With a notebook interface it's easy to do that. It is in fact one of the major advantages of an interactive notebook interface.
So first thing you should do before using MaximalBy
: try it out and see what it does! Look it up in the documentation and check the examples.
You'll see that MaximalBy
always returns a list of results, regardless of how many results are there. There can be zero, one or multiple results.
In[13]:= values = {{1, 2}, {2, 2}, {3, 1}};
In[17]:= MaximalBy[{}, Last]
Out[17]= {}
In[18]:= MaximalBy[values, First]
Out[18]= {{3, 1}}
In[19]:= MaximalBy[values, Last]
Out[19]= {{1, 2}, {2, 2}}