Loading...
Loading...
A hostel mess wallet records the net money change for each of n days. Money added is positive, money spent is negative, and a quiet day is 0.
Count the stretches of one or more consecutive days whose total change is exactly k.
Example 1
Input
5 3 1 2 1 2 1
Output
4
Days 1–2, 2–3, 3–4 and 4–5 each add up to 3.
Example 2
Input
6 0 3 -3 2 -2 0 1
Output
6
With negative values, many stretches can cancel out to 0.
Try the problem first. Open one hint at a time.
Because values can be negative, a growing and shrinking window does not work here.
Let total be the sum of days 1 to j. A stretch ending at day j adds up to k when an earlier running total equals total - k.
Keep a HashMap from each running total to how many times it has appeared so far.
Put total 0 in the map once before you start: it stands for "before day 1", so stretches that start on day 1 are counted.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor