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
Longest Non-decreasing Subarray From Two Arrays INPUT nums1: 2 3 1 i=0 i=1 i=2 nums2: 1 4 2 i=0 i=1 i=2 At each index i: Choose nums1[i] OR nums2[i] for nums3[i] Goal: Maximize length of non-decreasing subarray ALGORITHM STEPS 1 Initialize DP dp1=dp2=1 (prev lengths) 2 Iterate each index Track best ending at each 3 Check transitions 4 cases: n1--n1, n1--n2... 4 Update max length Track global maximum Space-Optimized DP State Index dp1 dp2 max 0 1 1 1 1 2 2 2 2 1 3 3 dp1: ends with nums1[i] dp2: ends with nums2[i] FINAL RESULT Optimal nums3 construction: 1 nums2[0] 3 nums1[1] 4 nums2[1] One optimal nums3: 1 3 4 1 <= 3 <= 4 Length = 3 OUTPUT 3 [OK] Max length found! Using O(1) space Key Insight: At each position i, we track TWO values: the longest non-decreasing subarray ending with nums1[i] and ending with nums2[i]. We only need the previous position's values, allowing O(1) space instead of O(n). For each transition, check if prev value <= current value to extend the subarray, otherwise reset to 1. TutorialsPoint - Longest Non-decreasing Subarray From Two Arrays | Space-Optimized DP
Asked in
Google 15 Microsoft 12 Amazon 8
12.0K Views
Medium Frequency
~25 min Avg. Time
450 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