Ctrl K

Best Run From Two Rows

Medium
You are given two arrays upper and lower of the same length n, two rows of a table with n columns. From each column i you pick exactly one number: either upper[i] or lower[i]. The picked numbers, in column order, form a new array of length n. Make your picks so that the new array contains the longest possible contiguous non-decreasing stretch (each element is at least the previous one). Return the length of that stretch.
Example 1
upper=[4, 2, 6, 1], lower=[1, 5, 3, 7] → 4

Take 4 from the top, 5 from the bottom, 6 from the top, 7 from the bottom: 4, 5, 6, 7 never decreases, length 4.

Example 2
upper=[3, 9, 2], lower=[8, 1, 2] → 2

For example 3, 9 or 1, 2, length 2. Three in a row is impossible: nothing fits after 9 or 8, and 1 is smaller than both options in the first column.

Example 3
upper=[5], lower=[2] → 1

There is a single column, so the answer is 1.

Constraints
  • 1 ≤ n ≤ 10⁵
  • len(upper) = len(lower) = n
  • 1 ≤ upper[i], lower[i] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFewest Jumps to the End MediumMost Profitable Streak MediumReach the Last Cell MediumWarehouse Cart Routes MediumCheapest Corner-to-Corner Route Medium
loading Python…
Input
upper=[4, 2, 6, 1], lower=[1, 5, 3, 7]
Expected
4

Run checks the first 3 tests in your browser. Submit checks all 125 tests on the server, hidden ones included.