Leetcode #2771: Longest Non-decreasing Subarray From Two Arrays
In this guide, we solve Leetcode #2771 Longest Non-decreasing Subarray From Two Arrays in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: nums1 = [2,3,1], nums2 = [1,2,1]
Output: 2
Explanation: One way to construct nums3 is:
nums3 = [nums1[0], nums2[1], nums2[2]] => [2,2,1].
The subarray starting from index 0 and ending at index 1, [2,2], forms a non-decreasing subarray of length 2.
We can show that 2 is the maximum achievable length.
Python Solution
class Solution:
def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:
n = len(nums1)
f = g = 1
ans = 1
for i in range(1, n):
ff = gg = 1
if nums1[i] >= nums1[i - 1]:
ff = max(ff, f + 1)
if nums1[i] >= nums2[i - 1]:
ff = max(ff, g + 1)
if nums2[i] >= nums1[i - 1]:
gg = max(gg, f + 1)
if nums2[i] >= nums2[i - 1]:
gg = max(gg, g + 1)
f, g = ff, gg
ans = max(ans, f, g)
return ans
Complexity
The time complexity is , where is the length of the array. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.