返回介绍

solution / 2700-2799 / 2712.Minimum Cost to Make All Characters Equal / README_EN

发布于 2024-06-17 01:03:01 字数 3890 浏览 0 评论 0 收藏 0

2712. Minimum Cost to Make All Characters Equal

中文文档

Description

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_.

Invert a character means if its value is '0' it becomes '1' and vice-versa.

 

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.

 

Constraints:

  • 1 <= s.length == n <= 105
  • s[i] is either '0' or '1'

Solutions

Solution 1

class Solution:
  def minimumCost(self, s: str) -> int:
    ans, n = 0, len(s)
    for i in range(1, n):
      if s[i] != s[i - 1]:
        ans += min(i, n - i)
    return ans
class Solution {
  public long minimumCost(String s) {
    long ans = 0;
    int n = s.length();
    for (int i = 1; i < n; ++i) {
      if (s.charAt(i) != s.charAt(i - 1)) {
        ans += Math.min(i, n - i);
      }
    }
    return ans;
  }
}
class Solution {
public:
  long long minimumCost(string s) {
    long long ans = 0;
    int n = s.size();
    for (int i = 1; i < n; ++i) {
      if (s[i] != s[i - 1]) {
        ans += min(i, n - i);
      }
    }
    return ans;
  }
};
func minimumCost(s string) (ans int64) {
  n := len(s)
  for i := 1; i < n; i++ {
    if s[i] != s[i-1] {
      ans += int64(min(i, n-i))
    }
  }
  return
}
function minimumCost(s: string): number {
  let ans = 0;
  const n = s.length;
  for (let i = 1; i < n; ++i) {
    if (s[i] !== s[i - 1]) {
      ans += Math.min(i, n - i);
    }
  }
  return ans;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文