Intuition
Try every possible subarray by fixing a start index and extending the end index, accumulating the running sum.
Explanation
Brute Force
For each starting index i, compute the running sum as we extend j from i to n-1. Whenever the running sum equals k, increment the count.
Two nested loops give O(n^2) time. Space is O(1) since we only track the running sum.
Why it is slow: Every pair (i, j) is examined, leading to quadratic time on large arrays.
Implementation
class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
int total = 0;
for (int j = i; j < nums.length; j++) {
total += nums[j];
if (total == k) {
count++;
}
}
}
return count;
}
}