I have the following array
int[] a = { 4, 5, 6, 5, 4, 3 };
i would like to search the array for the flat sequences, and return the longest flat sequence in the array.
for this array the answer would be 3 (5,6,5)
is there a way to do it without using a loop?
CodePudding user response:
Technically you can use recursion but that doesn't really gets rid of a loop. You just dont write the keyword while
or for
public static void main(String[] args) {
int[] a = { 4, 5, 6, 5, 4, 3 };
System.out.println(sequenceRecursive(a, 0, 0, 0));
}
public static int sequenceRecursive(int[] arr, int startIndex, int longest, int sequence) {
if(startIndex <= 0) startIndex = 1;
if(startIndex >= arr.length) return longest 1;
if(arr[startIndex] > arr[startIndex - 1]){
sequence ;
if(sequence > longest) longest = sequence;
}else{
sequence = 0;
}
return sequenceRecursive(arr, startIndex, longest, sequence);
}