#2771
Longest Non-decreasing Subarray From Two Arrays
MediumArrayDynamic ProgrammingDynamic ProgrammingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses dynamic programming to keep track of the longest non-decreasing subarray ending at each index for both nums1 and nums2. This reduces the number of checks needed significantly.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two arrays dp1 and dp2 of length n to store the lengths of the longest non-decreasing subarrays ending with nums1[i] and nums2[i].
- 2Step 2: Iterate through the arrays from index 0 to n-1, updating dp1 and dp2 based on the previous values and the current elements from nums1 and nums2.
- 3Step 3: For each index, check if the current element can extend the previous non-decreasing subarray, updating the dp arrays accordingly.
- 4Step 4: The result is the maximum value found in dp1 and dp2.
solution.py18 lines
1def longest_non_decreasing_subarray(nums1, nums2):
2 n = len(nums1)
3 dp1 = [1] * n
4 dp2 = [1] * n
5 max_length = 1
6
7 for i in range(1, n):
8 if nums1[i] >= nums1[i - 1]:
9 dp1[i] = dp1[i - 1] + 1
10 if nums2[i] >= nums2[i - 1]:
11 dp2[i] = dp2[i - 1] + 1
12 if nums1[i] >= nums2[i - 1]:
13 dp1[i] = max(dp1[i], dp2[i - 1] + 1)
14 if nums2[i] >= nums1[i - 1]:
15 dp2[i] = max(dp2[i], dp1[i - 1] + 1)
16 max_length = max(max_length, dp1[i], dp2[i])
17
18 return max_lengthℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the arrays, and the space complexity is O(n) due to the storage of the dp arrays.
- 1Choosing the optimal value from two arrays can maximize the length of non-decreasing subarrays.
- 2Dynamic programming allows us to build solutions incrementally, reducing redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.