Блог пользователя a_journey

Автор a_journey, история, 8 лет назад, По-английски

Given an array a[] = {1, 1 ,1 , -1} . you have to find all the subarrays of the given array whose sum is exactly = k.

example : a[] = { 1 , 1 , 1 , -1 } and k = 1

Ans = 4 all 3 one's + range from [2,4]

There is an geeks_article for it but the explanation is not good and clear and also without proof .

Can anyone explain me how to solve this problem with some explanation !

Thanks !

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
8 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Use prefix sums. Let , then the sum of a subarray in [l, r] is equal to sum[r] - sum[l - 1].

If we iterate over all possible pairs (l, r), we get a complexity of O(n2).

Fix the right boundary, if we maintain the prefix sum of the left boundary in a set, the time complexity is . Note that the possible left boundary is nondecreasing as the right boundary increases, we can handle this with two-pointers technique and thus have a complexity of O(n).

»
7 лет назад, скрыть # |
 
Проголосовать: нравится -14 Проголосовать: не нравится

A simple solution is to traverse all the subarrays and calculate their sum. If sum is equal to the required sum then increment the count of subarrays. Print final count of subarrays.