<s>[INST] $X$ a random variable, where $-1\leq X\leq \frac{1}{2}, \mathbb E[X]=0$. What is the maximal value of $\mathbb E[X^2]$? $X$ a random variable, where $$-1\leq X\leq \frac{1}{2}, \mathbb E[X]=0$$ 

Find the maximal value of $\mathbb E[X^2]$.


I came across a similar question, asking if the following  inequality is always true $$\mathbb E[X^2]\leq \frac{1}{4}$$
The answer is no, for example:
$$\mathbb P(X=-1) = \frac{1}{3},\mathbb P(X=\frac{1}{2}) = \frac{2}{3}\implies\\ \mathbb E[X^2]= ((-1)^2)\cdot(\frac{1}{3})+(\frac{1}{2})^2\cdot(\frac{2}{3})=\\ \frac{1}{3} +\frac{2}{3\cdot 4} =\frac{1}{2}$$
I was wondering how can one find the maximum, for any discrete or continuos random variable.

Remark: I'm not sure this question has a "nice" solution. 
 [/INST] For the sake of generality say that $X\in [a,b]$ a.s. (this implies $a\leq 0$).
Since $X=\frac{b-X}{b-a}a + \frac{X-a}{b-a}b$ and the square function is convex, $X^2\leq \frac{b-X}{b-a}a^2 + \frac{X-a}{b-a}b^2$ and taking expectations, $$E(X^2)\leq \frac{b}{b-a}a^2 - \frac{a}{b-a}b^2 = -ab$$
This bound is tight: it is attained only for $X\sim \frac{b}{b-a} \delta_{a}+\frac{-a}{b-a} \delta_{b}$.
In the special case where $a=-1$ and $b=\frac 12$ this yields $E(X^2)\leq \frac 12$, with equality iff $X\sim \frac 13 \delta_{-1}+\frac 23 \delta_{1/2}$.
</s>