Longest Non-decreasing Subarray From Two Arrays
Problem
You are given two integer arrays nums1 and nums2, both of the same length n.
You must build a new array result of length n by choosing, for each index i from 0 to n - 1, either nums1[i] or nums2[i] to place at position i in result. Every position must be filled by picking one of the two available values at that index — you cannot mix values from a single index or skip a position.
Across all 2^n possible ways of making these choices, find the maximum possible length of a contiguous, non-decreasing subarray inside the resulting result array. Return that maximum length.
Rules to keep in mind:
- "Non-decreasing" means each element is greater than or equal to the one before it.
- You are free to choose differently at every index; the choice at one position does not constrain the choice at another, except through the value that ends up adjacent to it.
- A subarray of length 1 is always trivially non-decreasing, so the answer is always at least 1.
Examples
Example 1:
Input: nums1 = [2,3,1,5], nums2 = [3,2,4,5]
Output: 4
Explanation:
By selecting result = [2,3,4,5] (taking nums1[0], nums1[1], nums2[2], and either array at index 3), the entire array is non-decreasing, giving a subarray of length 4.
Example 2:
Input: nums1 = [1,3,2,2], nums2 = [2,2,3,4]
Output: 4
Explanation:
Choosing result = [1,2,3,4] (using nums1[0], nums2[1], nums2[2], nums2[3]) produces a fully non-decreasing array of length 4, which is the best possible.
Constraints
1 <= n <= 10^5wherenis the length ofnums1andnums2nums1.length == nums2.length1 <= nums1[i], nums2[i] <= 10^9
Solution
Sign in to get AI feedback on your answer. Your work is saved while you do.
Sign in to evaluate