I request you to provide insightful suggestions to improve the following code as well as an alternative algorithm to solve it.
Problem Specification:
We'll say that a "mirror" section in an array is a group of contiguous elements such that somewhere in the array, the same group appears in reverse order. For example, the largest mirror section in {1, 2, 3, 8, 9, 3, 2, 1} is length 3 (the {1, 2, 3} part). Return the size of the largest mirror section found in the given array.
maxMirror({1, 2, 3, 8, 9, 3, 2, 1}) → 3
maxMirror({1, 2, 1, 4}) → 3
maxMirror({7, 1, 2, 9, 7, 2, 1}) → 2
Solution:
public class MaxMirror {
public static void main(String[] args) {
MaxMirror max = new MaxMirror();
int[] nums = { 1, 2, 1, 4 };
System.out.println("The maximum length of the mirror is "
+ max.maxMirror(nums));
}
public int maxMirror(int[] nums) {
if (nums.length == 0) {
return 0;
}
// Reverse order of the array
int[] revNums = new int[nums.length];
for (int numIndex = nums.length - 1, revIndex = 0; numIndex >= 0; numIndex--, revIndex++) {
revNums[revIndex] = nums[numIndex];
}
// Hope the sub array of maximum length is the array itself
int subArraysToBeChecked = 1;
for (int len = nums.length; len > 1; len--) {
if (mirrorOfLengthLenExists(nums, revNums, len,
subArraysToBeChecked)) {
return len;
}
// Increase the number of sub-arrays to be checked
subArraysToBeChecked++;
}
// In the worst case return 1
return 1;
}
// Choose start and end i.e. sub-arrays to be checked
public boolean mirrorOfLengthLenExists(int[] nums, int[] revNums, int len,
int subArraysToBeChecked) {
int start = 0;
int end = len - 1;
for (int i = len; i <= nums.length; i++) {
if (mirrorExistsFromStartToEnd(nums, revNums, start, end,
subArraysToBeChecked)) {
return true;
}
start++;
end++;
}
return false;
}
// Check from start to end whether mirrored in the revNums
public boolean mirrorExistsFromStartToEnd(int[] nums, int[] revNums,
int start, int end, int subArraysToBeChecked) {
int revStart = 0;
for (int subArraysChecked = 1; subArraysChecked <= subArraysToBeChecked; subArraysChecked++) {
int noOfElementsEqual = 0;
for (int numIndex = start, revIndex = revStart; numIndex <= end; numIndex++, revIndex++) {
if (revNums[revIndex] != nums[numIndex]) {
break;
} else {
++noOfElementsEqual;
}
}
if (noOfElementsEqual == (end - start + 1)) {
return true;
}
revStart++;
}
return false;
}
}
maxMirror({1, 2, 1, 2, 1})
return? – 200_success yesterday