Skip to main content
Code Review

Return to Question

replaced http://codereview.stackexchange.com/ with https://codereview.stackexchange.com/
Source Link

A continuation of this this queston. The task's description can also be found there.

A continuation of this queston. The task's description can also be found there.

A continuation of this queston. The task's description can also be found there.

Source Link
pgerchev
  • 155
  • 2
  • 8

Finding the longest sequence of increasing numbers in an array

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:

  1. We never actually check the n-1 number at the start of the algorithm - instead we directly check if the n number and we process it. This is why I have added the currentNumbersSequence.add(numbersToBeProcessed[0]); code line before we go in the for loop.

  2. What if the last n number is bigger than n-1? That means that we do not go into the else 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 the for loop. However it leads to a very obvious code repetition.

lang-java

AltStyle によって変換されたページ (->オリジナル) /