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
Building the Optimal Non-Decreasing SequenceChoice Visualization2nums1[0]1nums2[0]321342Optimal Path: [2, 3, 3, 4]2334Non-decreasing sequence of length 4๐ŸŽฏ Key: Dynamic Programming tracks optimal choices at each step
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.
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
41.3K Views
Medium Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen