Skip to main content
Back to problems
#2771
Medium Algorithms

Longest non decreasing subarray from two arrays

Array Dynamic Programming
31.0% acceptance
Feb 25, 2026
649
24
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. For each index i in the range [0, n - 1], you can assign either nums1[i] or nums2[i] to nums3[i]. Your task is to maximize the length of the longest non-decreasing subarray in nums3 by choosing its values optimally. Return an integer representing the length of the longest non-decreasing subarray in nums3. Note: A subarray is a contiguous non-empty sequence of elements within an array.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn max_non_decreasing_length(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
    let n = nums1.len();
    // dp1[i] = length of longest non-decreasing subarray ending at i if we pick nums1[i]
    // dp2[i] = length of longest non-decreasing subarray ending at i if we pick nums2[i]
    let mut dp1 = vec![1i32; n];
    let mut dp2 = vec![1i32; n];
    let mut res = 1;
    for i in 1..n {
      if nums1[i] >= nums1[i - 1] { dp1[i] = dp1[i].max(dp1[i - 1] + 1); }
      if nums1[i] >= nums2[i - 1] { dp1[i] = dp1[i].max(dp2[i - 1] + 1); }
      if nums2[i] >= nums1[i - 1] { dp2[i] = dp2[i].max(dp1[i - 1] + 1); }
      if nums2[i] >= nums2[i - 1] { dp2[i] = dp2[i].max(dp2[i - 1] + 1); }
      res = res.max(dp1[i]).max(dp2[i]);
    }
    res
  }
}