Problem
You are given a 0-indexed array of n
integers differences
, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1)
. More formally, call the hidden sequence hidden
, then we have that differences[i] = hidden[i + 1] - hidden[i]
.
You are further given two integers lower
and upper
that describe the inclusive range of values [lower, upper]
that the hidden sequence can contain.
- For example, given
differences = [1, -3, 4]
,lower = 1
,upper = 6
, the hidden sequence is a sequence of length4
whose elements are in between1
and6
(inclusive).[3, 4, 1, 5]
and[4, 5, 2, 6]
are possible hidden sequences.[5, 6, 3, 7]
is not possible since it contains an element greater than6
.[1, 2, 3, 4]
is not possible since the differences are not correct.
Return the number of possible hidden sequences there are. If there are no possible sequences, return 0
.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
n == differences.length
1 <= n <= 10^5
-10^5 <= differences[i] <= 10^5
-10^5 <= lower <= upper <= 10^5
Solution
Method 1 - Using Prefix sum
- The differences array tells you the change in values for a sequence. Starting with some initial value (let’s call it
hidden[0]
), you can compute all subsequent values in the sequence using the differences. - You are tasked with finding how many valid sequences exist, such that the elements are within the range
[lower, upper]
. Here are key insights: - The sequence is fully determined if we know
hidden[0]
since all subsequent values can be calculated using the differences array. - Valid sequences have all values within
[lower, upper]
. Thus, we need to identify the range of values forhidden[0]
that does not produce values outside[lower, upper]
.
Here is the approach:
- Compute cumulative sums from the
differences
array to find the largest and smallest values in the generated sequence relative tohidden[0]
. - Find the range for
hidden[0]
that ensures all values remain within[lower, upper]
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
wheren
is the length of the differences array (cumulative sums involve a single traversal). - 🧺 Space complexity:
O(1)
as we only use a few variables for computation.