LeetCode-in-Java

3800. Minimum Cost to Make Two Binary Strings Equal

Medium

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:

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:

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:

Solution

public class Solution {
    public long minimumCost(String s, String t, int flipCost, int swapCost, int crossCost) {
        int len = t.length();
        int diff = 0;
        int one = 0;
        int zero = 0;
        char[] arr1 = s.toCharArray();
        char[] arr2 = t.toCharArray();
        for (int i = 0; i < len; i++) {
            if (arr1[i] != arr2[i]) {
                diff++;
                if (arr1[i] == '0') {
                    zero++;
                } else {
                    one++;
                }
            }
        }
        int min = Math.min(one, zero);
        long ans = 0;
        long costOfFlip = ((long) min * flipCost) * 2;
        long costOfSwap = ((long) min * swapCost);
        ans += Math.min(costOfFlip, costOfSwap);
        diff -= (min * 2);
        int oddLeft = diff % 2;
        int evenLeft = diff - oddLeft;
        long costOfCrossSwap =
                (((long) (evenLeft / 2) * crossCost) + ((long) (evenLeft / 2) * swapCost));
        long costOfFlipMain = ((long) evenLeft * flipCost);
        ans += Math.min(costOfCrossSwap, costOfFlipMain);
        ans += (long) oddLeft * flipCost;
        return ans;
    }
}