use a stack to store non-decreasing height sequence to get goal in linear time