MediumNo. 2771

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

Topics
Array, Dynamic Programming
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

PythonSolution
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

Time
O(n)where n is the length of the array
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
2770Maximum Number of Jumps to Reach the Last IndexMedium
0045Jump Game IIMedium
0053Maximum SubarrayMedium
0055Jump GameMedium
0063Unique Paths IIMedium
0064Minimum Path SumMedium

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.

Free to download. Check it runs on your machine, then pick a plan.