How can someone get this optimal solution in first go?

At first glance was thinking about the brute force solution.
Did you get this solution(optimal one) in first go ?

if yes then how ?