How to find total number of subarrays with sum atmost k?
Constrains :
-1e4 <= a[i] <= 1e4
1 <= n <= 1e5
# | User | Rating |
---|---|---|
1 | tourist | 3993 |
2 | jiangly | 3743 |
3 | orzdevinwang | 3707 |
4 | Radewoosh | 3627 |
5 | jqdai0815 | 3620 |
6 | Benq | 3564 |
7 | Kevin114514 | 3443 |
8 | ksun48 | 3434 |
9 | Rewinding | 3397 |
10 | Um_nik | 3396 |
# | User | Contrib. |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 156 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
10 | nor | 152 |
How to find total number of subarrays with sum atmost k?
Constrains :
-1e4 <= a[i] <= 1e4
1 <= n <= 1e5
Name |
---|
We can use sliding window technique to solve the problem.
Here, i and j represent starting and ending points of the sliding window.
Initially i = j = 0.
Now, we will traverse the whole array and try to add elements.
i think this approach won't work for neagitive elements
arr = [2,2,-1] target = 3 it won't count [2,2,-1] in the answer
Oh yes, sorry; in that case it would fail.
Convert the statement to it's equivalent in terms of prefix sums i.e $$$pre_r - pre_l <= k$$$.
Now iterating over $$$r$$$, we need to find number of $$$l$$$ such that $$$pre_l >= pre_r - k$$$, which can be computed using ordered set of all $$$pre_l$$$.
but in this case, I have to iterate on all the prefix values >= pre(r)-k. How you will handle this thing while iterating the array?
use pbds!
You can use pbds or alternatively, compress the values of the prefix sum and use a data structure like segment tree or fenwick tree to count the values.