#2712
Minimum Cost to Make All Characters Equal
specialist · 805 · lc medium +31 · verified · 54.2% accepted · 582 likes · top 46%
Description
You are given a 0-indexed binary string s of length n. Two operations are available: flip s[0..i] at cost i + 1, or flip s[i..n-1] at cost n - i. Return the minimum total cost to make all characters the same.
Example 1:
Input: s = "0011"
Output: 2
Explanation: Apply the second operation with i = 2 to obtain s = "0000" for a cost of 2. It can be shown that 2 is the minimum cost to make all characters equal.
Example 2:
Input: s = "010101"
Output: 9
Explanation: Apply the first operation with i = 2 to obtain s = "101101" for a cost of 3.
Apply the first operation with i = 1 to obtain s = "011101" for a cost of 2.
Apply the first operation with i = 0 to obtain s = "111101" for a cost of 1.
Apply the second operation with i = 4 to obtain s = "111110" for a cost of 2.
Apply the second operation with i = 5 to obtain s = "111111" for a cost of 1.
The total cost to make all characters equal is 9. It can be shown that 9 is the minimum cost to make all characters equal.
Code
1
2
3