[LeetCode] Longest Non-decreasing Subarray From Two Arrays

2771. Longest Non-decreasing Subarray From Two Arrays

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
int maxNonDecreasingLength(vector<int>& nums1, vector<int>& nums2) {
pair<long long, long long> dp1{0,0}, dp2{0,0};
long long res = 0;
for(int i = 0; i < nums1.size(); i++) {
int a = nums1[i], b = nums2[i];
pair<long long, long long> dpp1{a,1}, dpp2{b,1};
if(dpp1.first >= dp1.first) {
dpp1.second = max(dpp1.second, dp1.second + 1);
}
if(dpp1.first >= dp2.first) {
dpp1.second = max(dpp1.second, dp2.second + 1);
}
if(dpp2.first >= dp1.first) {
dpp2.second = max(dpp2.second, dp1.second + 1);
}
if(dpp2.first >= dp2.first) {
dpp2.second = max(dpp2.second, dp2.second + 1);
}
res = max({res, dpp1.second, dpp2.second});
swap(dp1,dpp1);
swap(dp2,dpp2);
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/09/PS/LeetCode/longest-non-decreasing-subarray-from-two-arrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.