Skip to main content

2771. Longest Non-decreasing Subarray From Two Arrays

let dp[i][0] = an integer representing the length of the longest non-decreasing subarray using nums1[i]

let dp[i][1] = an integer representing the length of the longest non-decreasing subarray using nums2[i]

class Solution:
def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:

n = len(nums1)

if n == 1:
return 1

dp = [[1] * 2 for i in range(n)]

res = 1


for i in range(1, n):

if nums1[i] >= nums2[i-1]:
dp[i][0] = max(dp[i][0], dp[i-1][1] + 1)

if nums1[i] >= nums1[i-1]:
dp[i][0] = max(dp[i][0], dp[i-1][0] + 1)

if nums2[i] >= nums2[i-1]:
dp[i][1] = max(dp[i][1], dp[i-1][1] + 1)

if nums2[i] >= nums1[i-1]:
dp[i][1] = max(dp[i][1], dp[i-1][0] + 1)

res = max(res, dp[i][0], dp[i][1])

return res