Longest Non-decreasing Subarray From Two Arrays - Problem
You are given two 0-indexed integer arrays nums1 and nums2 of length n.
Let's define another 0-indexed integer array, nums3, of length n. For each index i in the range [0, n - 1], you can assign either nums1[i] or nums2[i] to nums3[i].
Your task is to maximize the length of the longest non-decreasing subarray in nums3 by choosing its values optimally.
Return an integer representing the length of the longest non-decreasing subarray in nums3.
Note: A subarray is a contiguous non-empty sequence of elements within an array.
Input & Output
Example 1 — Basic Case
$
Input:
nums1 = [2,3,1], nums2 = [1,4,2]
›
Output:
2
💡 Note:
We can choose nums1[0]=2, nums1[1]=3, and either nums1[2]=1 or nums2[2]=2 to form [2,3,1] or [2,3,2]. In both cases, the longest non-decreasing subarray is [2,3] with length 2.
Example 2 — Minimum Size
$
Input:
nums1 = [1], nums2 = [2]
›
Output:
1
💡 Note:
With only one position, we can choose either nums1[0]=1 or nums2[0]=2. Either choice gives us an array of length 1, so the longest non-decreasing subarray has length 1.
Example 3 — All Increasing
$
Input:
nums1 = [1,2,3], nums2 = [4,5,6]
›
Output:
3
💡 Note:
Both arrays are already non-decreasing. We can choose either nums1 entirely to get [1,2,3] or nums2 entirely to get [4,5,6]. Both give us a non-decreasing subarray of length 3.
Constraints
- 1 ≤ nums1.length == nums2.length ≤ 105
- -109 ≤ nums1[i], nums2[i] ≤ 109
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code