Last active
June 11, 2021 05:31
-
-
Save xmichael446/0f16cb4ba1feccc6106fc64e196ea05f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Будем юзать динамическое программирование - храним мапу суммы элементов до текущего элемента. | |
# Два случая: | |
# 1. Либо подмассив с элементами от начала исходного массива до | |
# текущего элемента имеет сумму элементов равную К. | |
# 2. Либо существует более короткий подмассив (от некоторого | |
# среднего элемента) до этого элемента, и в этом случае разница | |
# между общей суммой до среднего элемента и общей суммой до этого элемента равна k. | |
from collections import defaultdict | |
def subarray_sum_to_k(nums, k): | |
dp, total, count = defaultdict(int, {0: 1}), 0, 0 | |
for num in nums: | |
total += num | |
diff = total - k | |
count += dp[diff] | |
dp[total] = dp[total] + 1 | |
return count |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment