Asked at Tower Research Capital
Theory: Algorithms Under a Complexity BoundRead the problem, hints and solution here. The editor needs a bigger screen: open this page on a laptop to write and run your code.
Available in Python and C++. You are solving it in C++. Switch to Python
Count the contiguous slices of a sequence of integers that sum to a target.
Slices are non-empty and counted by position, so the same contents at two different offsets count twice.
long long count_subarrays(const std::vector<long long>& values, long long target);
count_subarrays({1, 1, 1}, 2); // 2
The count is returned as a long long, because a long run of zeros has
\(n(n+1)/2\) slices.
count_subarrays({3, 4, 7, 2, -3, 1, 4, 2}, 7); // 4
count_subarrays({0, 0, 0}, 0); // 6
The zeros case is worth checking against your intuition: every pair of endpoints in a run of three zeros gives a slice summing to zero, and there are six of them.