LeetCode-in-Java

2145. Count the Hidden Sequences

Medium

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.

Return the number of possible hidden sequences there are. If there are no possible sequences, return 0.

Example 1:

Input: differences = [1,-3,4], lower = 1, upper = 6

Output: 2

Explanation: The possible hidden sequences are:

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:

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.

Constraints:

Solution

public class Solution {
    public int numberOfArrays(int[] diff, int lower, int upper) {
        int n = diff.length;
        if (lower == upper) {
            for (int j : diff) {
                if (j != 0) {
                    return 0;
                }
            }
        }
        int max = -(int) 1e9;
        int min = (int) 1e9;
        int[] hidden = new int[n + 1];
        hidden[0] = 0;
        for (int i = 1; i <= n; i++) {
            hidden[i] = hidden[i - 1] + diff[i - 1];
        }
        for (int i = 0; i <= n; i++) {
            if (hidden[i] > max) {
                max = hidden[i];
            }
            if (hidden[i] < min) {
                min = hidden[i];
            }
        }
        int low = lower - min;
        int high = upper - max;
        if (low > high) {
            return 0;
        }
        return (high - low) + 1;
    }
}