The former should be extracted and put into a method or just return the longest sequence if you're out of the loop (and this takes care of your concern #2). The latter can just be taken out of the if
condition. The code inside the for
loop can be written as follows:
This change allows you to remove the currentNumbersSequence.add(numbersToBeProcessed[0]);
line.
So, in short, the method should become something like the following (not tested):
if (numbersToBeProcessed.length == 0) {
return null;
}
List<Integer> longestIncreasingSequence = new ArrayList<Integer>();
List<Integer> currentNumbersSequence = new ArrayList<Integer>();
for (int i = 0; i < numbersToBeProcessed.length - 1; i++) {
int currentNumber = numbersToBeProcessed[i];
int previousNumber = numbersToBeProcessed[i - 1];
currentNumbersSequence.add(previousNumber);
if (currentNumber <= previousNumber) {
// 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();
}
}
// at the end of the loop always compare the two sequences.
if (currentNumbersSequence.size() > longestIncreasingSequence.size()) {
return currentNumbersSequence;
}
return longestIncreasingSequence;