Leetcode 2771: Longest Non-decreasing Subarray From Two Arrays

grid47
grid47
Exploring patterns and algorithms
Feb 3, 2024 6 min read

You are given two integer arrays, nums1 and nums2, both of the same length n. Your task is to construct a new array nums3 such that each element in nums3 is either taken from nums1 or nums2 at the same index. The goal is to maximize the length of the longest contiguous non-decreasing subarray in nums3.
Problem
Approach
Steps
Complexity
Input: Two 0-indexed integer arrays nums1 and nums2 of length n.
Example: nums1 = [1,4,2,3], nums2 = [2,1,3,4]
Constraints:
• 1 <= nums1.length == nums2.length == n <= 100,000
• 1 <= nums1[i], nums2[i] <= 1,000,000,000
Output: Return an integer representing the length of the longest non-decreasing subarray that can be formed in nums3.
Example: Output: 3
Constraints:
• The output should be a non-negative integer.
Goal: Determine the maximum length of a non-decreasing subarray that can be achieved by selecting elements optimally from nums1 and nums2.
Steps:
• Initialize two arrays dp1 and dp2 to store the lengths of non-decreasing subarrays ending at each index when nums3 is constructed using nums1 or nums2 respectively.
• Iterate through the arrays and update dp1 and dp2 based on the conditions for non-decreasing subarrays.
• At each step, maintain the maximum length encountered so far.
• Return the maximum length at the end of the loop.
Goal: Limits and conditions to ensure valid input and output.
Steps:
• The arrays nums1 and nums2 must have the same length.
• Elements in nums1 and nums2 are positive integers.
Assumptions:
• The length of nums1 and nums2 will not exceed 100,000.
• The values in nums1 and nums2 will not exceed 1,000,000,000.
Input: nums1 = [3,5,2,8], nums2 = [4,2,6,9]
Explanation: One possible nums3 could be [3,5,6,9], forming a non-decreasing subarray of length 4.

Input: nums1 = [1,3,2], nums2 = [2,2,2]
Explanation: Optimal nums3 = [1,2,2], with the longest non-decreasing subarray length of 3.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus