3
4
7
2
-3
1
4
2
[0][1][2][3][4][5][6][7]
Brute force · every subarray
▸1given arr, k2count = 03for start in 0..n−1:4 sum = 05 for end in start..n−1:6 sum += arr[end]7 if sum == k: count++8return count
state
- k7
- count0
warming up the animation
Given an integer array and an integer k, return the total number of contiguous subarrays whose elements sum to exactly k.
▸1given arr, k2count = 03for start in 0..n−1:4 sum = 05 for end in start..n−1:6 sum += arr[end]7 if sum == k: count++8return count
line 1Count the contiguous subarrays whose elements sum to exactly k = 7. Brute force: fix a start, extend the end, keep a running sum, and tally every time it hits 7.