SparseOptimizerTerminateAction more flexible

Add an upper limit on the max number of iterations. Terminate the
optimizer if either the max number of iterations is met or the gain is
below the given threshold.