Longest Non-decreasing Subarray From Two Arrays — LeetCode 2771 Python Solution

MediumArrayDynamic Programming
Problem
#2771
Reading time
3 min

The 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.

Example

Input
nums1 = [2,3,1], nums2 = [1,2,1]
Output
2
Explanation
One way to construct nums3 is:

Python solution

Python
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

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2771. Longest Non-decreasing Subarray From Two Arrays is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2771. Longest Non-decreasing Subarray From Two Arrays?
LeetCode 2771. Longest Non-decreasing Subarray From Two Arrays is rated Medium on LeetCode.
What is the time complexity of LeetCode 2771. Longest Non-decreasing Subarray From Two Arrays?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 2771. Longest Non-decreasing Subarray From Two Arrays?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2771. Longest Non-decreasing Subarray From Two Arrays cover?
LeetCode 2771. Longest Non-decreasing Subarray From Two Arrays is tagged Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview