Getting the first category of the deepest level for an entry
Assuming you are only assigning one category (and thus by default all of that categories ancestors), then getting the 'last' returned category should work.

{% set category = entry.categories.last() %}


Otherwise, you will need some logic of some kind. What you have works, or perhaps something where you don't need to know how many levels there are.

{% set level = 0 %}
{% for category in entry.categories %}
    {% set level = category.level &gt; level ? category.level : level %}
{% endfor %}
{% set category = entry.categories.level(level).first %}


However, this will still not retrieve all the categories if there is more than one category set with same level.