Skip to content

Commit 36429b1

Browse files
committed
create 0560-subarray-sum-equals-k.cs
1 parent a6ae157 commit 36429b1

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

csharp/0560-subarray-sum-equals-k.cs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
public class Solution {
2+
/// <summary>
3+
/// Given an array of integers nums and an integer k, return the total number
4+
/// of continuous subarrays whose sum equals to k.
5+
/// </summary>
6+
/// <param name="nums">The input array of integers.</param>
7+
/// <param name="k">The target sum.</param>
8+
/// <returns>The total number of subarrays with sum equal to k.</returns>
9+
public int SubarraySum(int[] nums, int k) {
10+
int result = 0;
11+
int sum = 0;
12+
13+
// Create a dictionary to store the frequency of prefix sums
14+
// The key is the prefix sum, and the value is the frequency
15+
Dictionary<int, int> prefixSumFreq = new Dictionary<int, int>() { { 0, 1 }};
16+
17+
// Iterate through the array to calculate prefix sums and count subarrays
18+
for (int i = 0; i < nums.Length; i++) {
19+
sum += nums[i];
20+
21+
// If a prefix sum (sum - k) is present in the dictionary, it means there's a subarray with sum k
22+
if (prefixSumFreq.ContainsKey(sum - k)) {
23+
result += prefixSumFreq[sum - k];
24+
}
25+
26+
// Update the prefix sum frequency dictionary
27+
if (prefixSumFreq.ContainsKey(sum)) {
28+
prefixSumFreq[sum]++;
29+
}
30+
else {
31+
prefixSumFreq.Add(sum, 1);
32+
}
33+
}
34+
35+
return result;
36+
}
37+
}

0 commit comments

Comments
 (0)