C++ | EASY | DP | EXPLAINED
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\ndp1 stores the length of longest subarray if element at ith index is pick
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\ndp1 stores the length of longest subarray if element at ith index is picked from nums1.\ndp2 stores the length of longest subarray if element at ith index is picked from nums2.\n\n//inside for loop\n1.Choose the new element from nums1 with prev element from nums1\n2.Choose the new element from nums1 with prev element from nums2\n3.Choose the new element from nums2 with prev element from nums1\n4.Choose the new element from nums2 with prev element from nums2\n\nKeep track of maximum length\n\n# Complexity\n- Time complexity:\nO(N)\n- Space complexity:\nO(2N)\n\n# Code\n```\nclass Solution {\npublic:\n    int maxNonDecreasingLength(vector<int>& nums1, vector<int>& nums2) {\n        int n = nums1.size();\n        vector<int> dp1(n, 1);\n        vector<int> dp2(n, 1);\n        int maxi =1;\n        for(int i=1;i<n; i++){\n            if(nums1[i]>=nums1[i-1]){\n                dp1[i]= max(dp1[i], 1+dp1[i-1]);\n            }\n            if(nums1[i]>=nums2[i-1]){\n                dp1[i]= max(dp1[i], 1+dp2[i-1]);\n            }\n            if(nums2[i]>=nums1[i-1]){\n                dp2[i]= max(dp2[i], 1+dp1[i-1]);\n            }\n            if(nums2[i]>=nums2[i-1]){\n                dp2[i]= max(dp2[i], 1+dp2[i-1]);\n            }\n            maxi= max( maxi, max(dp1[i], dp2[i]));\n        }\n        return maxi;\n    }\n};\n```
['Dynamic Programming', 'C++']