Let $J_1:=\{i\in[n]\colon a_i\ge b_i\}$ and $J_2:=[n]\setminus J_1$, where $[n]:=\{1,\dots,n\}$. Without loss of generality (wlog), $M$ is a nonnegative integer; otherwise, $M$ can be replaced by $0\vee\lfloor M\rfloor$.
Let us temporarily remove the constraint that the $a_i$'s and $b_i$'s be integers; then the maximum value of $S$ may only increase (we shall see that it actually remains the same).
The values of $S$, $a_1+\dots+a_n$, $b_1+\dots+b_n$ will not change if we replace each of the $a_i$'s for $i\in J_1$ and each of the $b_i$'s for $i\in J_1$ by their respective arithmetic means over $i\in J_1$. Similarly, for $i\in J_2$. So, wlog $a_i=A_k$ and $b_i=B_k$ for $k=1,2$, some $A_k,B_k$ in $[0,M]$ such that $A_1\ge B_1$ and $A_2<B_2$, and all $i\in J_k$. Also, wlog $j:=|J_1|\le|J_2|=n-j$, so that $j\le m:=\lfloor n/2\rfloor$; here, $|\cdot|$ denotes the cardinality; the condition $a_1+\dots+a_n=b_1+\dots+b_n$ then becomes $j(A_1-B_1)=(n-j)(B_2-A_2)$, and we have
\begin{equation}
S=j(A_1-B_1)+(n-j)(B_2-A_2)=2j(A_1-B_1)\le2mM.
\end{equation}
The bound $2mM$ is attained if $a_1=\cdots=a_m=M$, $b_1=\cdots=b_m=0$, $a_{m+1}=\cdots=a_{2m}=0$, $b_{m+1}=\cdots=b_{2m}=M$, and $a_{2m+1}=b_{2m+1}=0$ in the case when $n$ is odd.
So, the maximum value of $S$ (both with and without the constraint that the $a_i$'s and $b_i$'s be integers) is $2mM=2\lfloor n/2\rfloor M$.
Remark. This solution holds if "positive integers" is understood as "nonnegative integers". If "positive integers" is understood as "strictly positive integers", then we can replace $a_i$, $b_i$, and $M$ by $a_i-1$, $b_i-1$, and $M-1$, respectively, to get nonnegative integers $a_i-1\in[0,M-1]$ and $b_i-1\in[0,M-1]$. In that case, the maximum will therefore be $2m(M-1)=2\lfloor n/2\rfloor(M-1)$; here it is assumed that $M$ is a strictly positive integer; otherwise, $M$ has to be replaced by $1\vee\lfloor M\rfloor$.