How to find total number of subarrays with sum atmost k?
Constrains :
-1e4 <= a[i] <= 1e4
1 <= n <= 1e5
# | User | Rating |
---|---|---|
1 | tourist | 3880 |
2 | jiangly | 3669 |
3 | ecnerwala | 3654 |
4 | Benq | 3627 |
5 | orzdevinwang | 3612 |
6 | Geothermal | 3569 |
6 | cnnfls_csy | 3569 |
8 | jqdai0815 | 3532 |
9 | Radewoosh | 3522 |
10 | gyh20 | 3447 |
# | User | Contrib. |
---|---|---|
1 | awoo | 161 |
1 | maomao90 | 161 |
3 | adamant | 156 |
4 | maroonrk | 153 |
5 | -is-this-fft- | 148 |
5 | SecondThread | 148 |
5 | atcoder_official | 148 |
8 | Petr | 147 |
9 | nor | 144 |
10 | TheScrasse | 142 |
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.
thankyou bro
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.