Solution for example 5

tl;dr