3
06/11/2024 7:00 am
Topic starter
Write a program to find all increasing sequences inside an array of integers. The integers are given in a single line, separated by a space. Print the sequences in the order of their appearance in the input array, each at a single line. Separate the sequence elements by a space. Find also the longest increasing sequence and print it at the last line. If several sequences have the same longest length, print the leftmost of them.
Note: the count of the input numbers is not explicitly specified, so you might need to read the sequence as string, then split it by a space and finally parse the obtained tokens to take their integer values.
Examples:

1 Answer
2
06/11/2024 7:00 am
Here is my solution, mate:
import java.util.ArrayList;
import java.util.Scanner;
public class Pr_04_LongestIncreasingSequence {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String[] input = console.nextLine().split(" ");
int[] array = new int[input.length];
ArrayList<Integer> longestList = new ArrayList<>();
ArrayList<Integer> currentList = new ArrayList<>();
for (int i = 0; i < input.length; i++) {
array[i] = Integer.parseInt(input[i]);
}
for (int i = 0; i < array.length; i++) {
if (i == (array.length - 1)) {
if (array[i - 1] < array[i]) {
System.out.print(array[i]);
currentList.add(array[i]);
if (currentList.size() > longestList.size()) {
longestList = currentList;
}
} else {
System.out.print(array[i]);
if (currentList.size() > longestList.size()) {
longestList = currentList;
}
currentList.clear();
currentList.add(array[i]);
}
} else if (array[i] < array[i + 1]) {
System.out.print(array[i] + " ");
currentList.add(array[i]);
} else {
System.out.println(array[i]);
if (currentList.size() > longestList.size()) {
longestList = currentList;
}
currentList.clear();
}
}
System.out.printf("\r\nLongest: ");
for (int i = 0; i < longestList.size(); i++) {
System.out.print(longestList.get(i) + " ");
}
}
}
