[LeetCode] Minimum Cost to Make Two Binary Strings Equal

3800. Minimum Cost to Make Two Binary Strings Equal

You are given two binary strings s and t, both of length n, and three positive integers flipCost, swapCost, and crossCost.

You are allowed to apply the following operations any number of times (in any order) to the strings s and t:

  • Choose any index i and flip s[i] or t[i] (change '0' to '1' or '1' to '0'). The cost of this operation is flipCost.
  • Choose two distinct indices i and j, and swap either s[i] and s[j] or t[i] and t[j]. The cost of this operation is swapCost.
  • Choose an index i and swap s[i] with t[i]. The cost of this operation is crossCost.

Return an integer denoting the minimum total cost needed to make the strings s and t equal.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
long long minimumCost(string S, string T, int flipCost, int swapCost, int crossCost) {
vector<long long> cnt{0,0};
for(int i = 0; i < S.length(); i++) if(S[i] != T[i]) cnt[S[i]-'0']++;
long long f = flipCost, s = swapCost, c = crossCost, p = min(s, 2 * f), diff = abs(cnt[0] - cnt[1]);
if(cnt[0] < cnt[1]) swap(cnt[0], cnt[1]);

long long res = diff * f + cnt[1] * p;
if(diff / 2 > 0 and c - 2 * f + p < 0) res += diff / 2 * (c - 2 * f + p);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/minimum-cost-to-make-two-binary-strings-equal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.