Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.nio.charset.StandardCharsets;
- import java.util.Arrays;
- public class LongestIncreasingSubsequence {
- public static void main(final String[] args) {
- try (final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8))) {
- int[] numbers = Arrays
- .stream(reader.readLine().trim().split("\\s+"))
- .mapToInt(Integer::parseInt)
- .toArray();
- int[] sequence = new int[numbers.length];
- int[] previous = new int[numbers.length];
- for (int currentIndex = 0; currentIndex < numbers.length; currentIndex++) {
- sequence[currentIndex] = 1;
- previous[currentIndex] = -1;
- for (int prevIndex = 0; prevIndex < currentIndex; prevIndex++) {
- if (numbers[prevIndex] < numbers[currentIndex] &&
- sequence[prevIndex] >= sequence[currentIndex]) {
- sequence[currentIndex] = sequence[prevIndex] + 1;
- previous[currentIndex] = prevIndex;
- }
- }
- }
- int lastIndex = -1;
- int maxLength = 0;
- for (int index = 0; index < numbers.length; index++) {
- if (maxLength < sequence[index]) {
- maxLength = sequence[index];
- lastIndex = index;
- }
- }
- int[] lis = new int[maxLength];
- while (lastIndex != -1) {
- lis[--maxLength] = numbers[lastIndex];
- lastIndex = previous[lastIndex];
- }
- System.out.println(Arrays.toString(lis).replaceAll("[,\\[\\]]", "").trim());
- } catch (IOException | NullPointerException e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment