You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<p>We define two variables $f$ and $g$, which represent the length of the longest non-decreasing subarray at the current position. Here, $f$ represents the length of the longest non-decreasing subarray ending with an element from $nums1$, and $g$ represents the length of the longest non-decreasing subarray ending with an element from $nums2$. Initially, $f = g = 1$, and the initial answer $ans = 1$.</p>
75478
+
<p>Next, we iterate over the array elements in the range $i \in [1, n)$, and for each $i$, we define two variables $ff$ and $gg$, which represent the length of the longest non-decreasing subarray ending with $nums1[i]$ and $nums2[i]$ respectively. When initialized, $ff = gg = 1$.</p>
75479
+
<p>We can calculate the values of $ff$ and $gg$ based on the values of $f$ and $g$:</p>
75480
+
<ul>
75481
+
<li>If $nums1[i] \ge nums1[i - 1]$, then $ff = \max(ff, f + 1)$;</li>
75482
+
<li>If $nums1[i] \ge nums2[i - 1]$, then $ff = \max(ff, g + 1)$;</li>
75483
+
<li>If $nums2[i] \ge nums1[i - 1]$, then $gg = \max(gg, f + 1)$;</li>
75484
+
<li>If $nums2[i] \ge nums2[i - 1]$, then $gg = \max(gg, g + 1)$.</li>
75485
+
</ul>
75486
+
<p>Then, we update $f = ff$ and $g = gg$, and update $ans$ to $\max(ans, f, g)$.</p>
75487
+
<p>After the iteration ends, we return $ans$.</p>
75488
+
<p>The time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.</p>
<p>The key to the problem is how to determine whether a node is a leaf node. We design a function $dfs(root, d)$, where $root$ represents the current node, and $d$ represents the depth of the current node. Each time we search, we update the answer $ans = \max(ans, d)$, and then determine whether the current node is a leaf node. If the current node has a left child, and the right child of the left child is not the current node, then we recursively call $dfs(root.left, d + 1)$. If the current node has a right child, and the left child of the right child is not the current node, then we recursively call $dfs(root.right, d + 1)$.</p>
75495
+
<p>The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree.</p>
0 commit comments