Quite a tricky problem I was stuck on trying to solve. Would appreciate some help on how to approach it.
Given an array, compute the number of subarrays with a mean = k
1 <= n <= 1e5
1 <= a[i], k <= 1e9
Thanks!
№ | Пользователь | Рейтинг |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3839 |
3 | Radewoosh | 3646 |
4 | jqdai0815 | 3620 |
4 | Benq | 3620 |
6 | orzdevinwang | 3612 |
7 | Geothermal | 3569 |
7 | cnnfls_csy | 3569 |
9 | ecnerwala | 3494 |
10 | Um_nik | 3396 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | Um_nik | 164 |
2 | maomao90 | 160 |
3 | -is-this-fft- | 159 |
4 | atcoder_official | 158 |
4 | awoo | 158 |
4 | cry | 158 |
7 | adamant | 155 |
8 | nor | 154 |
9 | TheScrasse | 152 |
10 | maroonrk | 151 |
Quite a tricky problem I was stuck on trying to solve. Would appreciate some help on how to approach it.
Given an array, compute the number of subarrays with a mean = k
1 <= n <= 1e5
1 <= a[i], k <= 1e9
Thanks!
Название |
---|
let's say dp store prefix sums.
So number of subarrays ending at j with their mean equal to k is the number of indexes who have dp[index]-index*k value equal to dp[j]-j*k.
Thank you so much for your tip, it helped me solve the problem!
Shouldn't you ask the source of the problem before you tell the approach ?
That problem is very common, I've seen it several times in different platforms/contests.
Others have explained the solution pretty well, but I think there's a nicer way to think about it.
A neat trick that I only learned about a few days ago is called the 'average trick' (that's what I call it, anyway). If you want a subarray $$$b$$$ to have an average of $$$k$$$, then the sum of $$$(b_i - k)$$$ is $$$0$$$. So what you can do is subtract $$$k$$$ from every element. Then you only need to check that the sum of $$$b_i$$$ is $$$0$$$.
This is a more common and easier to understand problem. If you store the prefix sums, all you need to do is find the number of pairs with the same sum (because then the latter minus the former will be 0).
$$$\newline$$$
Ahh, so when you subtract k from each element, it becomes a very standard problem (number of subarrays which sum to 0). This is incredibly elegant, thank you so much for sharing!!
This is a super cool trick, thanks for bringing it up!
I feel this too is needed Please correct if wrong: If(sum==0) ans++;