This is what I've gotten so far. What I've tried to do is go through and find the sequence using greater or equals too in an if statement. Then when that value no longer is greater or equal to the preveious number it goes into the else statement which records that sequence number and resets it so the count can begin again. All these sequence values are saved in an arraylist so that when I'm all done I can just do a simple comparison to find the greatest sequence number and return that. I need help with my first if/else statement that gathers the sequence data because I'm pretty sure this is where my issues are happening.
public class LongestSequence {
public static int getMaxSequence(ArrayList<Integer> list) {
int sequence = 0;
ArrayList<Integer> temp = new ArrayList<Integer>();
for (int i = 0; i < list.size() - 1; i++) {
//this is where things go wrong. I think.
if (list.get(i + 1) >= list.get(i)) {
sequence++;
} else {
//record the number in your arraylist
temp.add(sequence);
//reset count to 0
sequence = 0;
}
}
int greatestnum = 0;
for (int i = 0; i < temp.size() - 1; i++) {
if (temp.get(i) < temp.get(i + 1)) {
greatestnum = temp.get(i + 1);
} else {
greatestnum = temp.get(i);
}
}
return greatestnum;
}
You shouldn't have to use a temporary list for this. Just loop through the array or list with a counter and increment for each element that is greater than or equal to the previous. Use another variable to store the maximum:
int[] a = { 1, 2, 3, 4, 0, 19, 1, 1, 2, 2, 3, 3, 2 };
int count = 1, max = 1;
for (int i = 1; i < a.length; i++) {
if (a[i] >= a[i - 1]) {
count++;
} else {
count = 1;
}
if (count > max) {
max = count;
}
}
System.out.println(max);
6
Here, count
is the number of contiguous and sorted elements. We increment it while we're on a continuous/increasing streak. Once this streak breaks (else
clause), we check if count
is greater than max
, our variable for storing the maximum count: if it is, we set max
to count
. We then set count
back to 1, since in the else
clause we know our streak has ended and we'll need to start over.
(I've used an array here, but it should be trivial to convert the above code to work with lists).