A continuation of this queston. The task's description can also be found there.
After reformatting the code and getting rid of the ArrayIndexOutOfBounds
check,it now looks like this:
public static List<Integer> findLongestIncreasingSequence(int[] numbersToBeProcessed) {
if (numbersToBeProcessed.length == 0) {
return null;
}
List<Integer> longestIncreasingSequence = new ArrayList<Integer>();
List<Integer> currentNumbersSequence = new ArrayList<Integer>();
// the first number will be added always,no matter what
currentNumbersSequence.add(numbersToBeProcessed[0]);
for (int i = 1; i < numbersToBeProcessed.length; i++) {
int currentNumber = numbersToBeProcessed[i];
int previousNumber = numbersToBeProcessed[i - 1];
if (currentNumber > previousNumber) {
currentNumbersSequence.add(currentNumber);
} else {
// 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();
// after clearing add the current number as the first of the new
// sequence
currentNumbersSequence.add(currentNumber);
}
}
// at the end of the loop always compare the two sequences.
if (currentNumbersSequence.size() > longestIncreasingSequence.size()) {
longestIncreasingSequence.clear();
longestIncreasingSequence.addAll(currentNumbersSequence);
}
return longestIncreasingSequence;
}
There are couple of things that bother me about the algorithm above:
We never actually check the
n-1
number at the start of the algorithm - instead we directly check if then
number and we process it. This is why I have added thecurrentNumbersSequence.add(numbersToBeProcessed[0]);
code line before we go in thefor
loop.What if the last
n
number is bigger thann-1
? That means that we do not go into theelse
statement and the current sequence will never be compared against the largest one at this moment. This is why I had to add an extra check after thefor
loop. However it leads to a very obvious code repetition.