On the convexity of the value function for a class of nonconvex variational problems: existence and optimality conditions