How to find total number of subarrays with sum atmost k?
Constrains :
-1e4 <= a[i] <= 1e4
1 <= n <= 1e5
# | User | Rating |
---|---|---|
1 | jiangly | 3898 |
2 | tourist | 3840 |
3 | orzdevinwang | 3706 |
4 | ksun48 | 3691 |
5 | jqdai0815 | 3682 |
6 | ecnerwala | 3525 |
7 | gamegame | 3477 |
8 | Benq | 3468 |
9 | Ormlis | 3381 |
10 | maroonrk | 3379 |
# | User | Contrib. |
---|---|---|
1 | cry | 168 |
2 | -is-this-fft- | 165 |
3 | Dominater069 | 161 |
4 | Um_nik | 160 |
5 | atcoder_official | 159 |
6 | djm03178 | 157 |
7 | adamant | 153 |
8 | luogu_official | 150 |
9 | awoo | 149 |
10 | TheScrasse | 146 |
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.