A squadron of n drones flies in a single line, numbered 0 through n-1 from the front of the formation to the back. Each drone's identification beacon currently glows one of two colors, encoded as a binary string s of length n, where s[i] is '0' if the beacon at position i glows amber and '1' if it glows cyan.
The squadron leader can issue a resync command that targets a contiguous block of k drones counted from the very front of the line (for any 1 <= k <= n), or a contiguous block of k drones counted from the very back of the line. Issuing either command instantly toggles the color of every beacon inside the chosen block (amber becomes cyan and cyan becomes amber), and costs exactly k energy units -- one unit per drone touched.
The leader wants every beacon in the line to end up glowing the same color, using any number of resync commands in any order, while spending as little total energy as possible.
Print a single integer: the minimum total energy needed to make every beacon glow the same color.
Example 1
Input
4 0011
Expected
2
Explanation
s = "0011". The only position where adjacent beacons differ is between index 1 and index 2 (s[1]='0', s[2]='1'). Removing this mismatch costs min(2, 4-2) = 2: the leader can resync the front 2 drones (cost 2, turning "00" into "11" and giving "1111") or the back 2 drones (cost 2, giving "0000"). No cheaper combination exists, so the answer is 2.
Example 2
Input
2 10
Expected
1
Explanation
s = "10". The two beacons differ, and the single boundary at i=0 contributes min(1, 2-0-1) = 1. Resyncing just the front 1 drone (cost 1) turns "10" into "00", or resyncing just the back 1 drone (cost 1) turns it into "11" -- either way the cost is 1, which is optimal since at least one operation is required.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →