I have following task, form a given array, I want the longest ascending array. I will give you an example
int[] a = {19,12,13,1,2,3,4,5,14,23,24,25,26,31,32};
will return array of {1,2,3,4,5}
- that is the largest sequence of ascending numbers in the given array.
Below is the sample code:
int[] a = {19,12,13,1,2,3,4,5,14,23,24,25,26,27,31,32};
List<Integer> longestArray = new ArrayList<Integer>();
List<Integer> currentArary = new ArrayList<Integer>();
for (int i = 1; i < a.length; i++) {
if(currentArary.isEmpty()) {
currentArary.add(a[i-1]);
}
if (a[i]-1 == a[i-1]) {
currentArary.add(a[i]);
} else {
if(longestArray.size()<currentArary.size()) {
longestArray.clear();
longestArray.addAll(currentArary);
}
currentArary.clear();
}
}
System.out.println(longestArray);
Any feedback received on this method is more than welcome.
longestArray.clear(); longestArray.addAll(currentArary)
rather thanlongestArray = currentArary
? \$\endgroup\$