problems / 280

Suki's Treat Huddle

medium sliding-window arrays strings 1000 ms · 256 MB

Suki's Treat Huddle

Suki, the curly black dog with the grey beard and white paws, has a favourite circular path around the garden. Along it lie n spots, numbered 1 to n in order, and spot n is right next to spot 1, closing the loop. Each spot holds either one treat or nothing at all.

Suki would like to eat all her treats in one go, trotting along the path without passing an empty spot in between. Her owner can help: in one move, the owner picks any two spots (not necessarily next to each other) and swaps their contents.

Find the minimum number of moves needed so that all the treats occupy a set of consecutive spots around the circle. The stretch may wrap past spot n back to spot 1. If there are no treats, or the treats are already together, the answer is 0.

Input

The first line contains an integer n (1 ≤ n ≤ 10^6), the number of spots.

The second line contains a string of exactly n characters, each 0 or 1. The i-th character is 1 if spot i holds a treat and 0 if it is empty.

Output

Print one integer: the minimum number of swaps.

Notes

In the first example, the path is 1 0 1 0 0 1 1 (7 spots, 4 treats). Swapping spots 2 and 5 gives 1 1 0 0 0 1 1: the treats at spots 6, 7, 1 and 2 are consecutive because the path is a circle. The treats are not together at the start, so at least one move is needed, and the answer is 1. Without the wrap-around, two swaps would be needed.

In the second example, the treats at spots 1 and 6 are already together around the circle.

In the third example there are no treats at all.

Example 1

Input

7
1010011

Output

1

Example 2

Input

6
100001

Output

0

Example 3

Input

3
000

Output

0

Hints · reveal one at a time if you're stuck

Hint 1

Suppose you already knew exactly which stretch of spots the treats will end up in. How long is that stretch, and how many swaps does it take to fill it?

Hint 2

The final stretch has exactly as many spots as there are treats. Look at the empty spots inside it: what does each one need, and can a single swap ever fix two of them at once?

Hint 3

Now compare all n circular stretches of that fixed length. Recounting each one from scratch is too slow, but a sliding window updates the count in O(1) per step. Don't forget the stretches that wrap past spot n.

report an issue Prefer your own editor? sooks prep 280 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.