Skip to content

Commit aa333dd

Browse files
authored
Create 2771-longest-non-decreasing-subarray-from-two-arrays.js
1 parent b867094 commit aa333dd

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @param {number[]} nums1
3+
* @param {number[]} nums2
4+
* @return {number}
5+
*/
6+
var maxNonDecreasingLength = function(nums1, nums2) {
7+
const n = nums1.length
8+
let dp = Array(3).fill(1)
9+
let ans = 1
10+
const { max } = Math
11+
for(let i = 1; i < n; i++) {
12+
const nextDp = Array(3).fill(1)
13+
if (nums1[i] >= nums1[i - 1]) {
14+
nextDp[1] = max(nextDp[1], dp[1] + 1)
15+
}
16+
if (nums1[i] >= nums2[i - 1]) {
17+
nextDp[1] = max(nextDp[1], dp[2] + 1)
18+
}
19+
if (nums2[i] >= nums1[i - 1]) {
20+
nextDp[2] = max(nextDp[2], dp[1] + 1)
21+
}
22+
if (nums2[i] >= nums2[i - 1]) {
23+
nextDp[2] = max(nextDp[2], dp[2] + 1)
24+
}
25+
dp = nextDp
26+
// console.log(dp, nextDp)
27+
ans = max(ans, max(...dp))
28+
}
29+
return ans
30+
};
31+

0 commit comments

Comments
 (0)