2712. Minimum Cost to Make All Characters Equal Medium
1/**
2 * [2712] Minimum Cost to Make All Characters Equal
3 *
4 * You are given a 0-indexed binary string s of length n on which you can apply two types of operations:
5 *
6 * Choose an index i and invert all characters from index 0 to index i (both inclusive), with a cost of i + 1
7 * Choose an index i and invert all characters from index i to index n - 1 (both inclusive), with a cost of n - i
8 *
9 * Return the minimum cost to make all characters of the string equal.
10 * Invert a character means if its value is '0' it becomes '1' and vice-versa.
11 *
12 * <strong class="example">Example 1:
13 *
14 * Input: s = "0011"
15 * Output: 2
16 * 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.
17 *
18 * <strong class="example">Example 2:
19 *
20 * Input: s = "010101"
21 * Output: 9
22 * Explanation: Apply the first operation with i = 2 to obtain s = "101101" for a cost of 3.
23 * Apply the first operation with i = 1 to obtain s = "011101" for a cost of 2.
24 * Apply the first operation with i = 0 to obtain s = "111101" for a cost of 1.
25 * Apply the second operation with i = 4 to obtain s = "111110" for a cost of 2.
26 * Apply the second operation with i = 5 to obtain s = "111111" for a cost of 1.
27 * 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.
28 *
29 *
30 * Constraints:
31 *
32 * 1 <= s.length == n <= 10^5
33 * s[i] is either '0' or '1'
34 *
35 */
36pub struct Solution {}
37
38// problem: https://leetcode.com/problems/minimum-cost-to-make-all-characters-equal/
39// discuss: https://leetcode.com/problems/minimum-cost-to-make-all-characters-equal/discuss/?currentPage=1&orderBy=most_votes&query=
40
41// submission codes start here
42
43impl Solution {
44 pub fn minimum_cost(s: String) -> i64 {
45
46 }
47}
48
49// submission codes end
50
51#[cfg(test)]
52mod tests {
53 use super::*;
54
55 #[test]
56 fn test_2712() {
57 }
58}
59
Back
© 2025 bowen.ge All Rights Reserved.