Best C++ solution TC O(N*M) SC O(min(N,M))
\n\ntemplate \nstd::pair operator+(const std::pair &l, const std::pair &r)\n{\n    return {l.first + r.first, l.second + r.second};\n}\n\ntemplate \nstd::pair o
\n\ntemplate <typename T, typename U>\nstd::pair<T, U> operator+(const std::pair<T, U> &l, const std::pair<T, U> &r)\n{\n    return {l.first + r.first, l.second + r.second};\n}\n\ntemplate <typename T, typename U>\nstd::pair<T, U> operator-(const std::pair<T, U> &l, const std::pair<T, U> &r)\n{\n    return {l.first - r.first, l.second - r.second};\n}\n\ntypedef pair<int, int> p;\n\nclass Solution\n{public:\n\n    p decompose(int n)\n    {\n        int two = 0;\n        int five = 0;\n\n        while (n % 2 == 0)\n        {\n            two++;\n            n /= 2;\n        }\n\n        while (n % 5 == 0)\n        {\n            five++;\n            n /= 5;\n        }\n\n        return make_pair(two, five);\n    }\n\n\n    int maxTrailingZeros(vector<vector<int>> &grid)\n    {\n\n        vector<p> rows(grid.size(), make_pair(0, 0));\n        vector<p> cols(grid[0].size(), make_pair(0, 0));\n\n        for (int i = 0; i < grid.size(); i++)\n\n        {\n\n            for (int j = 0; j < grid[0].size(); j++)\n            {\n                auto pr = decompose(grid[i][j]);\n                rows[i].first += pr.first;\n                rows[i].second += pr.second;\n\n                cols[j].first += pr.first;\n                cols[j].second += pr.second;\n            }\n        }\n\n        vector<p> colstill(grid[0].size(), make_pair(0, 0));\n\n        int max0 = 0;\n\n        for (int i = 0; i < grid.size(); i++)\n\n        {\n            p rowtill = make_pair(0, 0);\n\n            for (int j = 0; j < grid[0].size(); j++)\n            {\n                auto a=decompose(grid[i][j]);\n\n                auto r = rows[i] - rowtill;\n\n                rowtill.first+=a.first;\n                rowtill.second+=a.second;\n\n                p l = rowtill;\n              \n\n                auto t = colstill[j];\n                auto b = cols[j] - colstill[j];\n                b.first-=a.first;\n                b.second-=a.second;\n                \n\n                int tz1 = min(l.first + t.first, l.second + t.second);\n                int tz2 = min(l.first + b.first, l.second + b.second);\n                int tz3 = min(r.first + t.first, r.second + t.second);\n                int tz4 = min(r.first + b.first, r.second + b.second);\n\n                max0 = max(max0, tz1);\n                max0 = max(max0, tz2);\n                max0 = max(max0, tz3);\n                max0 = max(max0, tz4);\n\n                colstill[j].first+=a.first;\n                colstill[j].second+=a.second;\n            }\n        }\n\n        return max0;\n    }\n};\n\n
[]