#2145

Count the Hidden Sequences

specialist · 770 · lc medium +31 · verified · 56.7% accepted · 1,040 likes · top 51%

Description

You are given a 0-indexed array of n integers differences that encodes the consecutive differences of a hidden sequence of length (n + 1). Specifically, if the hidden sequence is called hidden, then differences[i] = hidden[i + 1] - hidden[i].

You are also given two integers lower and upper bounding the values the hidden sequence may contain.

- For example, with differences = [1, -3, 4], lower = 1, upper = 6, the hidden sequence has length 4 and all elements must be in [1, 6].

- [3, 4, 1, 5] and [4, 5, 2, 6] are valid.

- [5, 6, 3, 7] is invalid since 7 > 6.

- [1, 2, 3, 4] is invalid since the differences don't match.

Return the number of valid hidden sequences. If none exist, return 0.

Example 1:

Input: differences = [1,-3,4], lower = 1, upper = 6
Output: 2
Explanation: The possible hidden sequences are:
- [3, 4, 1, 5]
- [4, 5, 2, 6]
Thus, we return 2.

Example 2:

Input: differences = [3,-4,5,1,-2], lower = -4, upper = 5
Output: 4
Explanation: The possible hidden sequences are:
- [-3, 0, -4, 1, 2, 0]
- [-2, 1, -3, 2, 3, 1]
- [-1, 2, -2, 3, 4, 2]
- [0, 3, -1, 4, 5, 3]
Thus, we return 4.

Example 3:

Input: differences = [4,-7,2], lower = 3, upper = 6
Output: 0
Explanation: There are no possible hidden sequences. Thus, we return 0.

Code

1
2
3