Coding problem
Count the stretches with a given total
The task
A ledger lists daily balance changes, which can be positive, negative or zero. An auditor wants to know how many stretches of consecutive days changed the balance by exactly k.
Complete CountRunsWithSum(int[] values, int k). Count the non-empty runs of neighbouring elements whose sum equals k. Runs at different positions count separately, even when they hold the same values. Return the count as a long.
Signature
public static long CountRunsWithSum(int[] values, int k)
Examples
[2, 1, 3], k = 3 →2. [2, 1] and [3].[3, 4, -7, 3], k = 3 →3. [3] at the start, the whole array, and [3] at the end.
Limits: Up to 400,000 values.
The tests check: an empty array, one value, runs that cancel out, overlapping runs, a negative k, no run at all, totals beyond int, and 400,000 zeros (a count beyond int, in time).
Hints
Your code
Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;
public static class Solution
{
// Counts the non-empty runs of neighbouring values whose sum equals k.
public static long CountRunsWithSum(int[] values, int k)
{
throw new NotImplementedException();
}
}This problem comes with TechInterviewNotes Full Access
Unlock all paid content on TechInterviewNotes.