C++, Time O(n), Space O(1), 4ms, beats 100%
If A[i] > B[i], we say, we have a upward node, elsewise we have a downward note.\n\nIf a node max(A[i],B[i]) < min(A[i+1],B[i+1]), we name it a free node.\nBeca
If A[i] > B[i], we say, we have a upward node, elsewise we have a downward note.\n\nIf a node max(A[i],B[i]) < min(A[i+1],B[i+1]), we name it a free node.\nBecause it can changed freely.\nOtherwise, a non-free node should have same direction with next node.\n\nSo, we find a chain, left of first node is a free node, end with a free node. All other node in chain should be non-free nodes.\nWe known: all nodes in chain should have same direction.\nFixup a chain need min(upward nodes, downward nodes) steps.\n\nSo we got the solution: just scan all chains!\n\n```C++\nstatic const int _ = []() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    return 0;\n}();\n\nclass Solution {\npublic:\n    int minSwap(vector<int>& A, vector<int>& B) {\n        int swaps = 0;\n        int up = 0, down = 0;\n        for (int i = 0; i < A.size(); ++i) {\n            if (A[i] > B[i])\n                up += 1;\n            else\n                down += 1;\n\n            if (i == A.size() - 1 || std::max(A[i], B[i]) < std::min(A[i + 1], B[i + 1])) {\n                // free node\n                swaps += std::min(up, down);\n                up = down = 0;\n            }\n        }\n        return swaps;\n    }\n};\n```
[]