NOTE
Subarray Sum Equals K
LeetCode notes on the brute-force solution for Subarray Sum Equals K.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Problem Description
Given an integer array and an integer k, find the number of contiguous subarrays whose sum equals k.
2. Approach
- Approach 1
- Brute force
- Use two nested loops to compute the sum
3. Implementation
3.1. Brute Force
package main
func subarraySum(nums []int, k int) int {
count := 0
for i := 0; i < len(nums); i++ {
sum := 0
for j := i; j < len(nums); j++ {
sum += nums[j]
if sum == k {
count++
}
}
}
return count
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub