Approach

This seems to be a greedy like problem, and I tried to walk the algorithm by-hand.

For a simple case, cross and swap operations can be done by two flips. Therefore, if the cost for cross or swap is larger than two flips, we simply replace it with two flips cost.

Then, we check when we need to use swap operation. Let’s say we have two sequence as follows s = 1 .. 0 t = 0 .. 1 If we want to eliminate the first difference by swapping, we need to find another (0, 1) pair to swap, since swapping with (0, 0) and (1, 1) did not change anything, this is just moving the difference backwards. So the greedy method is that we eliminate all the (1, 0) and (0, 1) pairs by swapping.

In the end we might get something like this: s= 1 1 0 0 1 0 | 0 0 0 0 0 | 0 0 1 1 t = 1 1 0 0 1 0 | 1 1 1 1 1 | 0 0 1 1 The first section is the pairs that is aligned by the swapping method. The second section is the remaining part that cannot be done by swapping. The last section is that it is initially being aligned.

For the remaining case, we can try to use cross and then do swap.can try to use cross and then do swap. This can eliminates two pairs, and notice that we can also use two flips to do this operation, so if two flip have smaller cost we use flip. s= 0 0 0 0 0 -> 0 0 0 0 1 -> 0 0 0 1 1 t = 1 1 1 1 1 -> 1 1 1 1 0 -> 1 1 1 0 0

In the end, there might be 1 pair that cannot be eliminate with cross and swap, then we use flip.

Code

class Solution {
public:
    long long minimumCost(string s, string t, int flip, int swap, int cross) {
        if(swap > 2*flip) swap = 2*flip;
        if(cross > 2*flip) cross = 2*flip;
        int n = s.size();
        int oneZero = 0;
        int zeroOne = 0;
        long long cost = 0;
        for(int i = 0 ; i < n ; ++i) {
            if(s[i] == '1' && t[i] == '0') ++oneZero;
            if(s[i] == '0' && t[i] == '1') ++zeroOne;
        }
        cost += ((long long)min(oneZero, zeroOne) * swap);
        
        int rem = max(oneZero, zeroOne) - min(oneZero, zeroOne);
        cost += ((long long)(rem / 2) * min(cross+swap, 2*flip));
        
        if(rem % 2 == 1) cost += flip;
        return cost;
    }
};