Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×

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

Автор nHimanshu, история, 16 месяцев назад, По-английски

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

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

»
16 месяцев назад, # |
Rev. 2   Проголосовать: нравится -9 Проголосовать: не нравится

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 месяцев назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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 месяцев назад, # |
  Проголосовать: нравится +1 Проголосовать: не нравится

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 месяцев назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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