Skip to content

2771. Longest Non-decreasing Subarray From Two Arrays 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int maxNonDecreasingLength(vector<int>& nums1, vector<int>& nums2) {
    int ans = 1;
    int dp1 = 1;  // the longest subarray that ends in nums1[i] so far
    int dp2 = 1;  // the longest subarray that ends in nums2[i] so far

    for (int i = 1; i < nums1.size(); ++i) {
      const int dp11 = nums1[i - 1] <= nums1[i] ? dp1 + 1 : 1;
      const int dp21 = nums2[i - 1] <= nums1[i] ? dp2 + 1 : 1;
      const int dp12 = nums1[i - 1] <= nums2[i] ? dp1 + 1 : 1;
      const int dp22 = nums2[i - 1] <= nums2[i] ? dp2 + 1 : 1;
      dp1 = max(dp11, dp21);
      dp2 = max(dp12, dp22);
      ans = max({ans, dp1, dp2});
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int maxNonDecreasingLength(int[] nums1, int[] nums2) {
    int ans = 1;
    int dp1 = 1; // the longest subarray that ends in nums1[i] so far
    int dp2 = 1; // the longest subarray that ends in nums2[i] so far

    for (int i = 1; i < nums1.length; ++i) {
      final int dp11 = nums1[i - 1] <= nums1[i] ? dp1 + 1 : 1;
      final int dp21 = nums2[i - 1] <= nums1[i] ? dp2 + 1 : 1;
      final int dp12 = nums1[i - 1] <= nums2[i] ? dp1 + 1 : 1;
      final int dp22 = nums2[i - 1] <= nums2[i] ? dp2 + 1 : 1;
      dp1 = Math.max(dp11, dp21);
      dp2 = Math.max(dp12, dp22);
      ans = Math.max(ans, Math.max(dp1, dp2));
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def maxNonDecreasingLength(self, nums1: list[int], nums2: list[int]) -> int:
    ans = 1
    dp1 = 1  # the longest subarray that ends in nums1[i] so far
    dp2 = 1  # the longest subarray that ends in nums2[i] so far

    for i in range(1, len(nums1)):
      dp11 = dp1 + 1 if nums1[i - 1] <= nums1[i] else 1
      dp21 = dp2 + 1 if nums2[i - 1] <= nums1[i] else 1
      dp12 = dp1 + 1 if nums1[i - 1] <= nums2[i] else 1
      dp22 = dp2 + 1 if nums2[i - 1] <= nums2[i] else 1
      dp1 = max(dp11, dp21)
      dp2 = max(dp12, dp22)
      ans = max(ans, dp1, dp2)

    return ans