How to find total number of subarrays with sum atmost k?
Constrains :
-1e4 <= a[i] <= 1e4
1 <= n <= 1e5
# | User | Rating |
---|---|---|
1 | jiangly | 4039 |
2 | tourist | 3841 |
3 | jqdai0815 | 3682 |
4 | ksun48 | 3590 |
5 | ecnerwala | 3542 |
6 | Benq | 3535 |
7 | orzdevinwang | 3526 |
8 | gamegame | 3477 |
9 | heuristica | 3357 |
10 | Radewoosh | 3355 |
# | User | Contrib. |
---|---|---|
1 | cry | 167 |
2 | -is-this-fft- | 165 |
3 | atcoder_official | 160 |
3 | Um_nik | 160 |
5 | djm03178 | 158 |
6 | Dominater069 | 156 |
7 | adamant | 153 |
8 | luogu_official | 151 |
8 | awoo | 151 |
10 | TheScrasse | 147 |
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.