It can be used both places because "the longest" is an adverbial phrase (Longest: adverb). Adverbs/adverbial phrases are quite flexible (some are limited) where you can place them. The one at the end gives "the longest" more emphasis or sounding uncertain. Specially if you extend the length of the word "longest" in an echo question.
Ex:
Asker -"Who is the person who remained THE LONGEST underwater?"
Replier (echo question) -"Who is the person who remained underwater THE LONGEST?" ummm this one person etc...
Also "the longest" in these cases, since you are using the word "the" which is a one time/person or the only instance. "The" will work with other adverbs that are similar. Who spend THE MOST time in the water? Who is THE slowest swimmer, Who is THE fastest swimmer? etc...
hope that helps.