Maximum length odd even subarray GFG
package datastrusture.array;
public class MaximumLength {
// Efficient soilution
public static int getMaximumLength(int[] arr) {
int n = arr.length;
int result = 1;
int max = 1;
for(int i = 1; i < n; i++) {
if(((arr[i - 1] % 2 != 0) && (arr[i] % 2 == 0)) || ((arr[i - 1] % 2 == 0) && (arr[i] % 2 != 0))){
result++;
max = Math.max(max,result);
}
else
result = 1;
}
return max;
}
// Finding maximum length odd-even subarray
public static int getLength(int[] arr){
int n = arr.length;
int result = 1;
for(int i = 0; i < n; i++) {
int count = 1;
for(int j = i + 1; j < n; j++){
if(((arr[j - 1] % 2 != 0) && (arr[j] % 2 == 0)) || ((arr[j - 1] % 2 == 0) && (arr[j] % 2 != 0))){
count++;
}
else break;
}
result = Math.max(result,count);
}
return result;
}
public static void main(String[] args) {
int[] array = {10,12,7,8,5};
System.out.print(getMaximumLength(array));
}
}
Comments
Post a Comment