Skip to content

Instantly share code, notes, and snippets.

@unilecs
Created June 11, 2021 00:49
Show Gist options
  • Save unilecs/a3aac1c98f87625d019dc8af0bc2e909 to your computer and use it in GitHub Desktop.
Save unilecs/a3aac1c98f87625d019dc8af0bc2e909 to your computer and use it in GitHub Desktop.
Задача: Найти подмассивы, где сумма элементов равна заданному числу K
using System;
using System.Collections.Generic;
public class Program
{
public static int FindSumOfSubarray(int[] arr, int k)
{
int total = 0;
int partSum = 0;
int len = arr.Length;
var dict = new Dictionary<int, int>();
dict.Add(0, 1);
for (int i = 0; i < len; i++)
{
partSum += arr[i];
// found a subarray that sum of this subarray equals k
if (dict.ContainsKey(partSum - k))
{
total += dict[partSum - k];
}
// add new part sum to dictionary
if (!dict.ContainsKey(partSum))
{
dict[partSum] = 0;
}
dict[partSum] += 1;
}
return total;
}
public static void Main()
{
Console.WriteLine("UniLecs");
// Tests
Console.WriteLine(FindSumOfSubarray(new int[] { 1, 2, 3 }, 3)); // 2
Console.WriteLine(FindSumOfSubarray(new int[] { 1, 2, 3 }, 4)); // 0
Console.WriteLine(FindSumOfSubarray(new int[] { 1, 2, 3 }, 5)); // 1
Console.WriteLine(FindSumOfSubarray(new int[] { 1, 1, 1 }, 2)); // 2
Console.WriteLine(FindSumOfSubarray(new int[] { 1, -1, 0 }, 0)); // 3
Console.WriteLine(FindSumOfSubarray(new int[] { 1 }, 0)); // 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment