How to find total number of subarrays with sum atmost k?
Constrains :
-1e4 <= a[i] <= 1e4
1 <= n <= 1e5
# | User | Rating |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
# | User | Contrib. |
---|---|---|
1 | cry | 164 |
1 | maomao90 | 164 |
3 | Um_nik | 163 |
4 | atcoder_official | 160 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
8 | Dominater069 | 154 |
8 | nor | 154 |
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.