An array with a length greater than 1 will be called a switching array if the element present at the odd position and the element present at an even position is equal.
For Example
[2,4,2,4] is a switching array because the element is present at even positions ie 0th position is 2 and 2nd position is 2 are equal, elements at odd positions ie 1st position is 4 and 3rd position is 4 are equal.
[3,7,3,7, 2, 1, 2] is not a switching array but has a switching subarray [3,7,3,7] of length 4 and [2, 1, 2] of length 3, hence the longest switching sub-array is [3,7,3,7] with length 4.
[1,5,6,0,1,0] is not a switching array but has a switching subarray [0,1,0] with length 3.
[7,-5,-5,-5,7,-1,7] is not a switching array but has a switching subarray [7,-1,7] of length 3 and [-5,-5,-5] of length 3.
package org.wesome.dsalgo;
public class SwitchingArray {
public static int switchingArray(int[] arr) {
if (arr.length == 1) {
return 1;
}
int even = arr[0], odd = arr[1];
int start = 0, max_len = 0;
for (int indx = 2; indx < arr.length; ++indx) {
System.out.println((indx + " % 2 != 0 " + (indx % 2 != 0) + " or " + (arr[indx] + " is even ") + (arr[indx] == even) + " and" + (" indx % 2 != 1 ") + (indx % 2 != 1) + ", " + (arr[indx] + " == odd ") + (arr[indx] == odd)));
if ((indx % 2 != 0 || arr[indx] == even) && (indx % 2 != 1 || arr[indx] == odd)) {
/* if condition is true then skip this iteration */
System.out.println("hence skip this iteration");
continue;
}
max_len = Math.max(max_len, indx - start);
start = indx - 1;
if (indx % 2 == 0) {
even = arr[indx];
odd = arr[indx - 1];
} else {
even = arr[indx - 1];
odd = arr[indx];
}
}
return Math.max(max_len, arr.length - start);
}
}
package org.wesome.dsalgo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class SwitchingArrayTest {
@Test
void switchingArrayTest1() {
int[] arr = new int[]{3, 2, 3, 2, 3};
Assertions.assertEquals(5, SwitchingArray.switchingArray(arr));
}
@Test
void switchingArrayTest2() {
int[] arr = new int[]{3, 7, 3, 7, 2, 1, 2};
Assertions.assertEquals(4, SwitchingArray.switchingArray(arr));
}
@Test
void switchingArrayTest3() {
int[] arr = new int[]{1, 5, 6, 0, 1, 0};
Assertions.assertEquals(3, SwitchingArray.switchingArray(arr));
}
@Test
void switchingArrayTest4() {
int[] arr = new int[]{7, -5, -5, -5, 7, -1, 7};
Assertions.assertEquals(3, SwitchingArray.switchingArray(arr));
}
}
plugins {
id 'java'
id "io.freefair.lombok" version "6.2.0"
}
group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}
test {
useJUnitPlatform()
}