First of all I'm a beginner programmer and I'm pretty sure I have quite a few errors in the code. I'm stuck in code in the exercise, sequence flat of integers if all the numbers in it are the same number or the series consists of two consecutive number, I need to write a recursive method which receives an array of integers, and returns the length of the maximum subset which is a flat series. For example for this array: (4, 5, 6, 5, 4, 3) The method will return 3. Since the sub-arrays that make up the flat series in the array are: (4, 5) - Length 2. (5, 6, 5) - Length 3. (5, 4) - Length 2. (4, 3) - Length 2. The longest flat sub-series in the array is 3 in length, which is the value to be returned.
public static int longestFlatSequence (int[] arr)
{
return lengthFlat (arr, 0, 0);
}
private static int lengthFlat (int[] arr, int i, int max)
{
if (arr.length >= 1)
{
return arr.length;
}
if (i + 1 <= arr.length -1)
{
if (arr[i] == arr[i+1] || arr[i] + 1 == arr[i+1])
{
int val = lengthFlatSequence(arr,i,i+1);
if (val > max)
{
max = val;
}
}
return lengthFlat(arr, i+1, max);
}
return max;
}
private static int lengthFlatSequence(int[] arr, int i, int curr)
{
if (i == arr.length - 1)
{
return curr;
}
int min = 0;
if (arr[i] < arr[i+1])
{
min = arr[i];
}else{
min = arr[i+1];
}
if (min == arr[curr] || min + 1 == arr[curr])
{
return lengthFlatSequence(arr, i, curr);
}else{
return curr;
}
}
Please help me fix the code. Thank you!