#include <iostream>
#include <cstdio>
#include <string>

using namespace std;

const int maxn = 2e3;

string f[maxn];
int g[maxn][maxn];
int ls[maxn][maxn];
int rs[maxn][maxn];
int us[maxn][maxn];
int ds[maxn][maxn];

int main()
{
    freopen("video.in", "r", stdin);
    freopen("video.out", "w", stdout);
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int n, m;
    cin >> n >> m;
    for (int i = 0; i < n; ++i) {
        cin >> f[i];
    }
    int t = 0;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            int i1 = (i+1)%n;
            int j1 = (j+1)%m;
            if (f[i1][j1] == f[i][j] && f[i1][j] == f[i][j] && f[i][j1] == f[i][j]) {
                g[i][j] = 1;
                ++t;
            }
        }
    }
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            if (i != 0) {
                us[i][j] += us[i-1][j];
            }
            us[i][j] += g[i][j];
            if (j != 0) {
                ls[i][j] += ls[i][j-1];
            }
            ls[i][j] += g[i][j];
        }
    }
    for (int i = n-1; i >= 0; --i) {
        for (int j = m-1; j >= 0; --j) {
            if (i != n-1) {
                ds[i][j] += ds[i+1][j];
            }
            ds[i][j] += g[i][j];
            if (j != m-1) {
                rs[i][j] += rs[i][j+1];
            }
            rs[i][j] += g[i][j];
        }
    }
    int res = 0;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            int c = ls[i][j]+rs[i][j]+us[i][j]+ds[i][j]-3*g[i][j];
            res = max(res, t-c);
        }
    }
    cout << res << '\n';
    return 0;
}
