Source: https://ocw.mit.edu/courses/6-006-introduction-to-algorithms-fall-2011/86d0fc7bd86543c73d6158a6711cb216_MIT6_006F11_ps5_sol.pdf