Problem : https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/description/
To reach the goal of this problem, we can:
The answer is minimum rotation count of the above 4 usecases.
class Solution {
public int minDominoRotations(int[] tops, int[] bottoms) {
int rotationCountForMatchingTop = helper(tops[0], tops, bottoms);
int rotationCountForMatchingBottom = helper(bottoms[0], tops, bottoms);
if (rotationCountForMatchingTop == -1 && rotationCountForMatchingBottom == -1)
return -1;
if (rotationCountForMatchingTop == -1)
return rotationCountForMatchingBottom;
if (rotationCountForMatchingBottom == -1)
return rotationCountForMatchingTop;
return Math.min(rotationCountForMatchingTop, rotationCountForMatchingBottom);
}
int helper(int target, int[] A, int[] B) {
int rotateToTop = 0, rotateToBottom = 0;
for (int i = 0; i < A.length; i++) {
if (target != A[i] && target != B[i]) {
// There is no way to rotate the current domino to match the target value.
return -1;
}
if (target != A[i]) {
rotateToTop += 1;
}
if (target != B[i]) {
rotateToBottom += 1;
}
}
return Math.min(rotateToTop, rotateToBottom);
}
}