#2712
Medium Algorithms Minimum cost to make all characters equal
String Dynamic Programming Greedy
54.2% acceptance
Feb 25, 2026
582
27
You are given a 0-indexed binary string s of length n on which you can apply two types of operations:
Choose an index i and invert all characters from index 0 to index i (both inclusive), with a cost of i + 1
Choose an index i and invert all characters from index i to index n - 1 (both inclusive), with a cost of n - i
Return the minimum cost to make all characters of the string equal.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn minimum_cost(s: String) -> i64 {
let s = s.as_bytes();
let n = s.len() as i64;
let mut cost = 0i64;
for i in 1..s.len() {
if s[i] != s[i - 1] {
cost += (i as i64).min(n - i as i64);
}
}
cost
}
}