✅ Explained: Only 6 line logic, O(n) time and O(1) space
Intuition\n Describe your first thoughts on how to solve this problem. \nSince we\'re dealing with subarrays (not subsequences), we would anyways look at the ex
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince we\'re dealing with subarrays (not subsequences), we would anyways look at the exact prev value for length computation. Hence, we can use a variable to keep track of length, instead of maintaining an array.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAt any index i,\n- lenSoFar1 = length so far till nums1[i - 1]\n- lenSoFar2 = length so far till nums2[i - 1]\n- newLen1 = length so far till nums1[i]\n- newLen2 = length so far till nums2[i]\n\nInitial values of all the above are 1. (since a subarray will have at least 1 element)\n\nCheck if nums1[i] can be placed after nums1[i - 1]. If yes, update newLen1. Then check if nums1[i] can be placed after nums2[i - 1]. If yes, in order to have the maximum length, we need to decide whether to follow nums1[i - 1] or nums2[i - 2]. Therefore, we check if 1 + lenSoFar2 > newLen1, only then we update newLen1. Repeat the same for nums2[i].\n\nThen update maxLen with the maximum of newLen1 and newLen2. Also, update lenSoFar1 and lenSoFar2 before entering the next pass of the for loop.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1) excluding input\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    int maxNonDecreasingLength(vector<int>& nums1, vector<int>& nums2) {\n        int n = nums1.size();\n        int maxLen = 1;\n        int lenSoFar1 = 1, lenSoFar2 = 1;\n\n        for (int i = 1; i < n; i++) {\n            int newLen1 = 1;\n            if (nums1[i] >= nums1[i - 1]) newLen1 = 1 + lenSoFar1;\n            if (nums1[i] >= nums2[i - 1] && 1 + lenSoFar2 > newLen1) newLen1 = 1 + lenSoFar2;\n\n            int newLen2 = 1;\n            if (nums2[i] >= nums2[i - 1]) newLen2 = 1 + lenSoFar2;\n            if (nums2[i] >= nums1[i - 1] && 1 + lenSoFar1 > newLen2) newLen2 = 1 + lenSoFar1;\n\n            lenSoFar1 = newLen1, lenSoFar2 = newLen2;\n            maxLen = max(maxLen, max(lenSoFar1, lenSoFar2));\n        }\n\n        return maxLen;\n    }\n};\n```
['C++']