Approach

We compare all pairs betweeb H and V pairs, and then store them in two vectors and then check the duplicate ones for eahc two vectors and that is the square that it can be formed.

But this method show be optimizzed further since the two vector is in O(N^2) order, and comparing them both require extra times. Acutally we only need to collect pairs for either H or V (using a hash), and then when we are doing the pairs in the other direction, we can check if it is already in the hash dircetly .

Code

class Solution {
public:
    int maximizeSquareArea(int m, int n, vector<int>& hFences, vector<int>& vFences) {
        sort(hFences.begin(), hFences.end());
        sort(vFences.begin(), vFences.end());
        hFences.insert(hFences.begin(), 1);
        vFences.insert(vFences.begin(), 1);
        hFences.push_back(m);
        vFences.push_back(n);

        unordered_set<int> dH;
        unordered_set<int> dV;
        for(int i = 0 ; i < hFences.size() ; ++i) {
            for(int j = i+1 ; j < hFences.size() ; ++j) {
                dH.insert(hFences[j]-hFences[i]);
            }
        }
        // don't use twice O(N*N)

        for(int i = 0 ; i < vFences.size() ; ++i) {
            for(int j = i+1 ; j < vFences.size() ; ++j) {
                int diff = vFences[j]-vFences[i];
                if(dH.count(diff)) {
                    dV.insert(diff);
                }
            }
        }

        long long ans = -1;
        for(const auto& w: dV) {
            ans = max(ans, (long long)w*w);
        }

        return ans == -1 ? -1 : ans % 1'000'000'007;
    }


    int maxWide;
};