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!

# | User | Rating |
---|---|---|

1 | tourist | 3822 |

2 | Benq | 3745 |

3 | ksun48 | 3560 |

4 | Radewoosh | 3538 |

5 | peehs_moorhsum | 3532 |

6 | Um_nik | 3489 |

7 | maroonrk | 3424 |

8 | Petr | 3380 |

9 | sunset | 3338 |

10 | ecnerwala | 3336 |

# | User | Contrib. |
---|---|---|

1 | 1-gon | 207 |

2 | Errichto | 181 |

2 | awoo | 181 |

4 | Um_nik | 180 |

5 | -is-this-fft- | 175 |

6 | maroonrk | 174 |

7 | Radewoosh | 172 |

7 | tourist | 172 |

9 | SecondThread | 170 |

10 | rng_58 | 166 |

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!

↑

↓

Codeforces (c) Copyright 2010-2021 Mike Mirzayanov

The only programming contests Web 2.0 platform

Server time: Jul/31/2021 15:32:29 (f2).

Desktop version, switch to mobile version.

Supported by

User lists

Name |
---|

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!

Code for anyone who is curiousShouldn'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.

Let

be total subarrays uptil index

with mean

.

So

where p are the prefix sums.

Lets see how,

We want the count of all subarrays that end at index i. This is equivalent to saying, :

which is nothing but

for all

we can maintain a map

and add the contribution of

to the answer.

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$$$

ImplementationAhh, 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!