Array-3 > maxMirror
prev | next | chance
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
Write the array forward and reverse, and look for the longest common sequence.It doesn't say so it in the challenge, but every element in an array will be a mirror sequence of length 1.
It doesn't say so it in the challenge, but every element in an array will be a mirror sequence of length 1.i was not clear on above. can you please elaborate on it? How every element in array is mirror sequence of length 1?
public int maxMirror(int[] nums) {
int len = nums.length;
int total = 0;
int highest = 0;
for (int x = 0; x < len; x++) {
total = 0;
for (int j = len - 1; x + total < len && j > -1; j--) {
if (nums[x + total] == nums[j]) {
total++;
} else {
if (total > 0) {
highest = Math.max(total, highest);
total = 0;
}
}
}
highest = Math.max(total, highest);
}
return highest;
}
Expected Run
maxMirror([1, 2, 3, 8, 9, 3, 2, 1]) → 3 3 OK
maxMirror([1, 2, 1, 4]) → 3 3 OK
maxMirror([7, 1, 2, 9, 7, 2, 1]) → 2 2 OK
maxMirror([21, 22, 9, 8, 7, 6, 23, 24, 6, 7, 8, 9, 25, 7, 8, 9]) → 4 4 OK
maxMirror([1, 2, 1, 20, 21, 1, 2, 1, 2, 23, 24, 2, 1, 2, 1, 25]) → 4 4 OK
maxMirror([1, 2, 3, 2, 1]) → 5 5 OK
maxMirror([1, 2, 3, 3, 8]) → 2 2 OK
maxMirror([1, 2, 7, 8, 1, 7, 2]) → 2 2 OK
maxMirror([1, 1, 1]) → 3 3 OK
maxMirror([1]) → 1 1 OK
maxMirror([]) → 0 0 OK
maxMirror([9, 1, 1, 4, 2, 1, 1, 1]) → 3 3 OK
maxMirror([5, 9, 9, 4, 5, 4, 9, 9, 2]) → 7 7 OK
maxMirror([5, 9, 9, 6, 5, 4, 9, 9, 2]) → 2 2 OK
maxMirror([5, 9, 1, 6, 5, 4, 1, 9, 5]) → 3 3 OK
other tests
OK
package com.solution;
public class MaxMirror {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] ar = { 1, 2, 3, 8, 9, 3, 2, 1 };
int[] ar1 = { 1, 2, 1, 4};
//System.out.println("value===>" + maxMirror(ar));
System.out.println("value===>" + maxMirror(ar1));
}
public static int maxMirror(int[] nums) {
int len = nums.length;
int total = 0;
int highest = 0;
for (int x = 0; x < len; x++) {
total = 0;
for (int j = len - 1; x + total < len && j > -1; j--) {
if (nums[x + total] == nums[j]) {
total++;
} else {
if (total > 0) {
highest = Math.max(total, highest);
total = 0;
}
}
}
highest = Math.max(total, highest);
}
return highest;
}
}