where is the angle between the force and the infinitesimal displacement dx. Note that in the special case where the force is constant (and ) we get the familiar W = Fd.
Thus for your problem:
What you need to do here is verify the direction of the displacement versus the alternating directions of the applied force. When the object starts moving the displacement and force are in the same direction. At x = 4 the direction of the force switches signs so now we need to be subtracting. Now at some point we may also have to account for a change in direction of the displacement. This can be discovered by looking at the overall work done by the force up to a given time: If and when this becomes negative then the object has changed its direction of motion.
All in all this is a fairly complicated problem and is difficult to work out for an arbitrary a and b.
Knowing me, however, there is a simpler approach. I always wind up doing things the hard way.