3800. Minimum Cost to Make Two Binary Strings Equal
Description
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
iand flips[i]ort[i](change'0'to'1'or'1'to'0'). The cost of this operation isflipCost. - Choose two distinct indices
iandj, and swap eithers[i]ands[j]ort[i]andt[j]. The cost of this operation isswapCost. - Choose an index
iand swaps[i]witht[i]. The cost of this operation iscrossCost.
Return an integer denoting the minimum total cost needed to make the strings s and t equal.
Example 1:
Input: s = "01000", t = "10111", flipCost = 10, swapCost = 2, crossCost = 2
Output: 16
Explanation:
We can perform the following operations:
- Swap
s[0]ands[1](swapCost = 2). After this operation,s = "10000"andt = "10111". - Cross swap
s[2]andt[2](crossCost = 2). After this operation,s = "10100"andt = "10011". - Swap
s[2]ands[3](swapCost = 2). After this operation,s = "10010"andt = "10011". - Flip
s[4](flipCost = 10). After this operation,s = t = "10011".
The total cost is 2 + 2 + 2 + 10 = 16.
Example 2:
Input: s = "001", t = "110", flipCost = 2, swapCost = 100, crossCost = 100
Output: 6
Explanation:
Flipping all the bits of s makes the strings equal, and the total cost is 3 * flipCost = 3 * 2 = 6.
Example 3:
Input: s = "1010", t = "1010", flipCost = 5, swapCost = 5, crossCost = 5
Output: 0
Explanation:
The strings are already equal, so no operations are required.
Constraints:
n == s.length == t.length1 <= n <= 1051 <= flipCost, swapCost, crossCost <= 109sandtconsist only of the characters'0'and'1'.
Solutions
Solution 1
Thinking
Only positions where \(s\) and \(t\) differ need work. With \(n \le 10^5\), searching operation sequences is infeasible.
Matching bits can stay as they are. Mismatches fall into two types: \(s[i]=\texttt{0}\) and \(t[i]=\texttt{1}\), or the reverse. Let their counts be \(d_0\) and \(d_1\).
A flip fixes any mismatch; an in-string swap pairs one type with the other; a cross swap changes the gap between the two counts. The optimum is therefore the cheapest among all-flips, pairing then flipping the leftover, and balancing with cross swaps before pairing.
We count the two mismatch types and compare those three closed-form costs, without simulating individual operations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |