How many subarrays add up to 7? A subarray from j + 1 to i sums to prefix[i] - prefix[j], so it hits 7 exactly when some earlier prefix equals prefix[i] - 7. Keep a count of every prefix seen so far, starting with 0 for the empty prefix, and each index answers in one lookup.
Counting subarrays with sum 7 over 8 values.
i = 0: prefix becomes 3, so a subarray ending here sums to 7 if an earlier prefix was 3 - 7 = -4. Never seen, so none ends here. Then record prefix 3.
Index 0, prefix 3, count 0.
i = 1: prefix becomes 7, so a subarray ending here sums to 7 if an earlier prefix was 7 - 7 = 0. Seen 1 time, before the start: count rises to 1. Then record prefix 7.
Index 1, prefix 7, count 1.
i = 2: prefix becomes 14, so a subarray ending here sums to 7 if an earlier prefix was 14 - 7 = 7. Seen 1 time, after index 1: count rises to 2. Then record prefix 14.
Index 2, prefix 14, count 2.
i = 3: prefix becomes 16, so a subarray ending here sums to 7 if an earlier prefix was 16 - 7 = 9. Never seen, so none ends here. Then record prefix 16.
Index 3, prefix 16, count 2.
i = 4: prefix becomes 10, so a subarray ending here sums to 7 if an earlier prefix was 10 - 7 = 3. Seen 1 time, after index 0: count rises to 3. Then record prefix 10.
Index 4, prefix 10, count 3.
i = 5: prefix becomes 11, so a subarray ending here sums to 7 if an earlier prefix was 11 - 7 = 4. Never seen, so none ends here. Then record prefix 11.
Index 5, prefix 11, count 3.
i = 6: prefix becomes 15, so a subarray ending here sums to 7 if an earlier prefix was 15 - 7 = 8. Never seen, so none ends here. Then record prefix 15.
Index 6, prefix 15, count 3.
i = 7: prefix becomes 17, so a subarray ending here sums to 7 if an earlier prefix was 17 - 7 = 10. Seen 1 time, after index 4: count rises to 4. Then record prefix 17.
Index 7, prefix 17, count 4.
4 subarrays sum to 7. One pass with a hash map of prefix counts: O(n) instead of the O(n squared) of trying every pair of ends, and negative values are no problem because prefixes are looked up, not scanned.
4 subarrays found.