I have the following task: to find the largest sequence of increasing numbers in an array.
I'll give you an example : 2 3 4 1 50 2 3 4 5
will return the sequence of 2 3 4 5
- that is the largest sequence of increasing numbers in the given array.
Another one is : 5 -1 10 20 3 4
which will return -1 10 20
.
If there are two equal sequences -for example 4 5 1 2 -1
which has the sequences 4 5
and 1 2
the first sequence will be returned.
Below is my method
public static List<Integer> findLongestIncreasingSequence(int[] numbersToBeProcessed) {
List<Integer> longestIncreasingSequence = new ArrayList<Integer>();
List<Integer> currentNumbersSequence = new ArrayList<Integer>();
for (int i = 0; i < numbersToBeProcessed.length; i++) {
int currentNumber = numbersToBeProcessed[i];
int nextNumber = 0;
// checks if it is not the last number in the array
if (i != numbersToBeProcessed.length - 1) {
nextNumber = numbersToBeProcessed[i + 1];
}
currentNumbersSequence.add(currentNumber);
//checks if the current sequence ends here(the next number is smaller or equal)
//or if the array ends
if (currentNumber >= nextNumber || i == numbersToBeProcessed.length - 1) {
// checks if the current sequence is bigger
if (currentNumbersSequence.size() > longestIncreasingSequence.size()) {
longestIncreasingSequence.clear();
longestIncreasingSequence.addAll(currentNumbersSequence);
}
//clear the current sequence so it can start all over again
currentNumbersSequence.clear();
}
}
return longestIncreasingSequence;
}
Any feedback received on this method is more than welcome. The thing I dislike the most is the check I make for the last element in order to avoid ArrayIndexOutOfBounds
exception.