DDSA
Advertisement

2145. Count the Hidden Sequences

Time: O(n)
Space: O(1)

Approach

Compute prefix sum of differences; answer = (upper - lower) - (max_prefix - min_prefix) + 1.

2145.cs
C#
// Approach: Compute prefix sum of differences; answer = (upper - lower) - (max_prefix - min_prefix) + 1.
// Time: O(n) Space: O(1)

public class Solution
{
    public int NumberOfArrays(int[] differences, int lower, int upper)
    {
        long prefix = 0;
        long mn = 0; // Starts from 0.
        long mx = 0; // Starts from 0.

        foreach (var d in differences)
        {
            prefix += d;
            mn = Math.Min(mn, prefix);
            mx = Math.Max(mx, prefix);
        }

        return (int)Math.Max(0L, (upper - lower) - (mx - mn) + 1);
    }
}
Advertisement
Was this solution helpful?