JavaScript O(n) time and O(1) space, 2 pointers solution
To get the best answer we want to maximize j and minimize i, while maintaining 2 invariants:\n i <= j\n nums1[i] <= nums2[j]\n\nThis can be translated almost di
To get the best answer we want to maximize j and minimize i, while maintaining 2 invariants:\n* i <= j\n* nums1[i] <= nums2[j]\n\nThis can be translated almost directly to code:\n\n```javascript\nvar maxDistance = function(nums1, nums2) {\n    let i = 0, j = 0;\n    \n    let ans = 0;\n    while (i < nums1.length && j < nums2.length) {\n        // maintain the i <= j invariant\n        j = Math.max(j, i);\n        \n        // we want to maximize j so move it forward whenever possible\n        while (nums1[i] <= nums2[j]) {\n            ans = Math.max(ans, j - i);\n            j++;\n        }\n        \n        // we want to minimize i so move it forward only to maintain invariants\n        i++;\n    }\n    \n    return ans;\n};\n```
['Two Pointers', 'JavaScript']