Java | DP | With comments | Easy to understand
Intuition\nNeed to use DP, since our current decision will effect which options are available for our future decisions.\n\n# Approach\nUse a 2D array to store t
# Intuition\nNeed to use DP, since our current decision will effect which options are available for our future decisions.\n\n# Approach\nUse a 2D array to store the lengths of non-decreasing subarrays ending at each index, considering two choices:\n- Choice 1: Using nums1[i]\n- Choice 2: Using nums2[i]\n\nThe first dimension of the 2D array represents the index \'i\',\nand the second dimension represents the choice between nums1 and nums2.\n\nAlgorithm:\n1. Initialize the dynamic programming table:\n   - Since any element itself is a non-decreasing subarray, if there is just 1 element, the maximum length is 1.\n   - Set dp[0][0] and dp[0][1] to 1 for both choices nums1 and nums2.\n   - Set maxLen to 1.\n\n2. Fill the dynamic programming table:\n   - Iterate from index 1 to n-1, where n is the length of the input arrays.\n   - For each index \'i\', calculate the lengths of the longest non-decreasing subarrays ending at \'i\' using different choices.\n   - Update dp[i][0]:\n       - If nums1[i] is greater than or equal to nums1[i-1], extend the non-decreasing subarray ending at index i-1.\n       - If nums1[i] is greater than or equal to nums2[i-1], extend the non-decreasing subarray ending at index i-1 using nums2.\n   - Update dp[i][1]:\n       - If nums2[i] is greater than or equal to nums2[i-1], extend the non-decreasing subarray ending at index i-1.\n       - If nums2[i] is greater than or equal to nums1[i-1], extend the non-decreasing subarray ending at index i-1 using nums1.\n   - Update maxLen by taking the maximum value among maxLen, dp[i][0], and dp[i][1].\n\n3. Return maxLen, which represents the length of the longest non-decreasing subarray.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\n//  Dynamic Programming | 2D Array | O(n) Time | O(n) Space\nclass Solution {\n        public int maxNonDecreasingLength(int[] nums1, int[] nums2) {\n    int n = nums1.length;\n    int[][] dp = new int[n][2];\n    int maxLen = 0;\n\n    // Initialize the dynamic programming table\n    dp[0][0] = dp[0][1] = 1;\n    maxLen = 1;\n\n    // Fill the dynamic programming table\n    for (int i = 1; i < n; i++) {\n        dp[i][0] = dp[i][1] = 1;\n\n        // For nums1\n        if (nums1[i] >= nums1[i - 1]) {\n            dp[i][0] = dp[i - 1][0] + 1;\n        }\n        if (nums1[i] >= nums2[i - 1]) {\n            dp[i][0] = Math.max(dp[i][0], dp[i - 1][1] + 1);\n        }\n\n        // For nums2\n        if (nums2[i] >= nums2[i - 1]) {\n            dp[i][1] = dp[i - 1][1] + 1;\n        }\n        if (nums2[i] >= nums1[i - 1]) {\n            dp[i][1] = Math.max(dp[i][1], dp[i - 1][0] + 1);\n        }\n\n        maxLen = Math.max(maxLen, Math.max(dp[i][0], dp[i][1]));\n    }\n\n    return maxLen;\n}\n\n}\n```
['Java']