I try to solve an exercise about collection about find the longest sequence of a List Integer Check my code
public void findLongestSequence(List<Integer> values)
{
List<Integer> result = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
for (int i = 1; i < values.size(); i ) {
temp.add(values.get(i-1));
if(values.get(i)<values.get(i-1))
{
if(temp.size()>= result.size())
{
result.clear();
result.addAll(temp);
temp.clear();
}
}
}
System.out.println(values);
System.out.println(result);
}
The problem is my code is never check the value of the last element.
Input : List list = List.of(7, 2, 7, 1, 2, 3, 8, 1, 2, 3, 4, 5);
Result : [1, 2, 3, 8]
Expected : [1,2,3,4,5]
CodePudding user response:
it happens because of you skip the last value having the temp.add(values.get(i-1));
I've fixed it for you:
public static void findLongestSequence(List<Integer> values) {
List<Integer> result = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
for (int i = 0; i < values.size(); i ) {
temp.add(values.get(i));
if ((values.size() == i 1) || values.get(i) > values.get(i 1)) {
if (temp.size() >= result.size()) {
result.clear();
result.addAll(temp);
}
temp.clear();
}
}
System.out.println(values);
System.out.println(result);
}