Longest Non-decreasing Subarray From Two Arrays - Problem
You're given two parallel arrays nums1 and nums2, each of length n. Your mission is to create the optimal third array by choosing either nums1[i] or nums2[i] at each position i.
The goal is to maximize the length of the longest non-decreasing subarray in your constructed array. A non-decreasing subarray means each element is greater than or equal to the previous one.
Example:
If nums1 = [2, 3, 1] and nums2 = [1, 2, 3]
You could create [2, 3, 3] by choosing indices [0, 0, 1] respectively
This gives you a non-decreasing subarray of length 3!
Return the maximum possible length of the longest non-decreasing subarray you can achieve.
Input & Output
example_1.py โ Basic Case
$
Input:
nums1 = [2,3,1], nums2 = [1,2,3]
โบ
Output:
3
๐ก Note:
We can construct [2,3,3] by choosing nums1[0], nums1[1], nums2[2]. This gives us a non-decreasing subarray of length 3: [2,3,3].
example_2.py โ Optimal Switching
$
Input:
nums1 = [1,3,2,1], nums2 = [2,2,3,4]
โบ
Output:
4
๐ก Note:
We can construct [2,2,3,4] by choosing nums2[0], nums2[1], nums2[2], nums2[3]. This entire array is non-decreasing with length 4.
example_3.py โ Single Element
$
Input:
nums1 = [1], nums2 = [2]
โบ
Output:
1
๐ก Note:
With only one position, we can choose either 1 or 2, giving us a non-decreasing subarray of length 1.
Constraints
- 1 โค nums1.length == nums2.length โค 105
- 1 โค nums1[i], nums2[i] โค 109
- Both arrays have the same length
Visualization
Tap to expand
Understanding the Visualization
1
State Tracking
At each position, track the best sequences ending with each choice
2
Smart Transitions
Extend previous states only when the non-decreasing property is maintained
3
Optimal Choice
Choose the path that gives the maximum overall length
Key Takeaway
๐ฏ Key Insight: By tracking the best sequence length ending with each choice at every position, we can build the optimal solution without exploring all combinations.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code