KatInterview

Longest Strictly Rising Window After One Edit

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashingarrayssliding-windowprefix-suffix

Last updated

Find the longest contiguous strictly increasing window in an integer array after replacing at most one element with any integer, using prefix and suffix run lengths.

Longest Strictly Rising Window After One Edit

You are given a list of integers readings. You may overwrite at most one position with any integer you like. The new value can be positive, negative or zero, and it does not need to appear anywhere else in the list. You may also leave the list unchanged.

After this optional edit, look for a contiguous block of the list in which every value is strictly greater than the one before it.

Return the greatest possible length of such a block, taking the best choice of edit (or no edit).

Rules

  • "Strictly greater" means equal neighbors do not count as rising.
  • The replacement value must be an integer, so two neighbors can be bridged only if at least one integer lies strictly between them.
  • A list with a single element yields 1. A list with no elements yields 0.
  • The input list is only edited conceptually. You only need to return a length.

Constraints

  • 1 <= len(readings) <= 10^5
  • -10^9 <= readings[i] <= 10^9
  • The replacement value may be any integer, with no bound.

Examples

Example 1

Input: longest_rising_window_with_edit([1, 2, 8, 4, 5])

Output: 5

Example 2

Input: longest_rising_window_with_edit([5, 4, 3, 2, 1])

Output: 2

Hints

Hint 1

Without any edit, the answer is just the longest run of strictly increasing consecutive values. Think about how to record, for every index, the run length ending there and the run length starting there.

Hint 2

If you rewrite position i, you can always make it extend one neighbouring run by one: pick a huge value to extend the run on its left, or a tiny value to extend the run on its right.

Hint 3

To join the run ending at i-1 with the run starting at i+1, the new value must be an integer strictly between readings[i-1] and readings[i+1]. That is possible only when readings[i+1] - readings[i-1] >= 2.