LeetCode 2771: Longest Non-decreasing Subarray From Two Arrays Solution

Master LeetCode problem 2771 (Longest Non-decreasing Subarray From Two Arrays), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2771. Longest Non-decreasing Subarray From Two Arrays

Problem Explanation

Explanation:

To maximize the length of the longest non-decreasing subarray in nums3, we can iterate through the arrays nums1 and nums2 and choose the optimal value at each index of nums3. We will track the length of the longest non-decreasing subarray found so far.

We can solve this problem by dynamic programming. We will define a DP array where dp[i] represents the length of the longest non-decreasing subarray ending at index i in nums3. At each index i, we will consider two possibilities:

  1. If nums1[i] >= nums1[i-1] and nums2[i] >= nums2[i-1], we can choose either nums1[i] or nums2[i] to extend the non-decreasing subarray ending at index i.
  2. If nums1[i] >= nums1[i-1] and nums2[i] < nums2[i-1] or vice versa, we must choose the value that maintains the non-decreasing property.

The final answer will be the maximum value in the DP array. :

Solution Code

public int maxNonDecreasingSubarray(int[] nums1, int[] nums2) {
    int n = nums1.length;
    int[] dp = new int[n];
    dp[0] = 1;
    
    for (int i = 1; i < n; i++) {
        dp[i] = 1;
        if (nums1[i] >= nums1[i-1] && nums2[i] >= nums2[i-1]) {
            dp[i] = Math.max(dp[i], dp[i-1] + 1);
        }
        if (nums1[i] >= nums2[i-1]) {
            dp[i] = Math.max(dp[i], dp[i-1] + 1);
        }
        if (nums2[i] >= nums1[i-1]) {
            dp[i] = Math.max(dp[i], dp[i-1] + 1);
        }
    }
    
    int maxLen = 0;
    for (int len : dp) {
        maxLen = Math.max(maxLen, len);
    }
    
    return maxLen;
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2771 (Longest Non-decreasing Subarray From Two Arrays)?

This page provides optimized solutions for LeetCode problem 2771 (Longest Non-decreasing Subarray From Two Arrays) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2771 (Longest Non-decreasing Subarray From Two Arrays)?

The time complexity for LeetCode 2771 (Longest Non-decreasing Subarray From Two Arrays) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2771 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2771 in Java, C++, or Python.

Back to LeetCode Solutions