Please read the new rule regarding the restriction on the use of AI tools. ×

nHimanshu's blog

By nHimanshu, history, 16 months ago, In English

Problem Description

Given an array A of N length and you are also given number B.

You need to find the number of subarrays in A having sum less than B. We may assume that there is no overflow.

Problem Constraints 1 <= N <= 10000, -100<=A[i]<=100, 0<=B<=10000

Example: INPUT:: A----> [1,−2,4,8], B=0, OUTPUT: 2

  • Vote: I like it
  • -4
  • Vote: I do not like it

| Write comment?
»
16 months ago, # |
Rev. 2   Vote: I like it -9 Vote: I do not like it

I think that the answer for the example input should be 3. 1. a[1,1] , sum=1 .... 2. a[2,2] , sum=-2 .... 3. a[1,2] , sum=-1.... are the possible subarrays

Edit: Sorry I thought B=2.

»
16 months ago, # |
  Vote: I like it 0 Vote: I do not like it

If n<=10000 actually, you can do prefix sum then for each [l,r] check the answer. If you have a typo and n<=100000, maintain a segment tree / BIT for dynamic range queries. Now for each i , increase the frequency of sum of [1,i] in the tree by 1, and add to the answer the frequencies of the range that makes the sum of [1,i] less than b

»
16 months ago, # |
  Vote: I like it +1 Vote: I do not like it

You can maintain an ordered multiset storing the prefix sums before the i'th index dynamically. Let's say you are standing at the i'th index, so you should have all prefix sums stored till the i-1'th index to be precise.

Now, we want to calculate how many subarrays ending at the i'th index have a Sum < B . So you need to search how many previous subarray prefixes are there which you can remove. More precisely, you need to find how many subarray prefixes have a [ sum >= current_sum-b+1 ] . So you can find it from the ordered set in O(log(N)) time on an average. So overall you can do it in approximately NlogN operations which would suffice the given constraints for sure.

I haven't been able to think of a O(N) solution till now.

Implementation(C++)
»
16 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Can you provide link where can I submit this task. Thanks