Here’s an easy way to see that a spacecraft firing it’s engine in the gravity well of even a stationary planet can leave it with more momentum after leaving the well than it would have firing its engine outside the well, as Kevbo and FrankH have been arguing.
Case 1: Consider a spacecraft whose mass excluding propellent is M, moving a velocity V0 towards a stationary planet, starting at some large distance R. It will take some time, T1 to reach closest approach, where it will have a larger velocity, V0 + dV1. dV1 is due to the gravitational pull of the planet. After an additional time T1 leaving the vicinity of the planet, its velocity will be back down to V0 when it is again at distance R from the planet. It then fires its engine, giving it final velocity V0 + dVp.
Case 2: Again, the spacecraft is moving with an initial velocity V0 towards the planet, startig at distance R. It then fires its engine, giving it velocity V0 + Vp. It will take some time, T2 to reach closest approach, where it will have a larger velocity, V0 + dVp + dV2. Assuming the engine is fired to accelerate the spacecraft in the direction it is moving, T2 will be smaller than T1. Since momentum is (the integral of) force * time, dV2 < dV1. This doesn’t affect the final velocity, however. After an additional time T2 leaving the vicinity of the planet, its velocity will be back to V0 + dVp at distance R, the same final velocity as case 1.
Case 3: Again, the spacecraft is moving a velocity V0 towards the planet. Like the first case, it will take time T1 to reach closest approach, where it will have the velocity, V0 + dV1. It then fires its engine, giving it velocity V0 + dV1 + Vp. After an additional time T3 to get to a distance R from the planet, its velocity will be
V0 + dVp + dV1 - dV3.
Since the engine was fired at closest approach, the spacecraft is travelling faster on its outward leg than on its inward leg, so T3 < T1. Thus dV3 < dV1, and the final velocity in Case 3 is greater than in the other two cases.
To avoid the complication of the gravitational force not being directly in line with the spacecraft’s motion, the cases can be further simplified: Imagine the spacecraft is falling straight towards the planet’s center, and that the planet has a hole, so the spacecraft can pass through unimpeded. Then it reduces to a one-dimensional problem.