Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* 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. */
- import java.util.ArrayList;
- import java.util.Scanner;
- public class _04_LongestIncreasingSequence {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Scanner scan = new Scanner(System.in);
- System.out.println("Enter the Elements of your Array on single line, separated by a space:");
- String inputLine = scan.nextLine();
- if (!inputLine.isEmpty()) {
- System.out.println("The All Increasing Sequences of elements in your Array are:");
- String[] numStr = inputLine.split("[\\s]+");
- if (numStr.length > 1) {
- int[] numberArr = new int[numStr.length];
- for (int i = 0; i < numberArr.length; i++) {
- numberArr[i] = Integer.parseInt(numStr[i]);
- }
- findAndPrintAllIncreasingSequencesInArrayOfIntegers(numberArr);
- } else {
- System.out.println(numStr[0]);
- System.out.println("Longest: " + numStr[0]);
- }
- } else {
- System.out.println("Error! - Input Array is Empty!!!");
- }
- }
- private static void findAndPrintAllIncreasingSequencesInArrayOfIntegers(
- int[] numbers) {
- int longestSeqLength = 1;
- int startIndex = 0;
- int elementsCounter = 1;
- int indexElements = 0;
- StringBuilder sequence = new StringBuilder();
- sequence.append(numbers[0]);
- for (int i = 1; i < numbers.length; i++) {
- if (numbers[i] > numbers[i - 1]) {
- sequence.append(' ').append(numbers[i]);
- elementsCounter++;
- } else {
- if (elementsCounter > longestSeqLength) {
- longestSeqLength = elementsCounter;
- startIndex = indexElements;
- }
- System.out.println(sequence);
- indexElements = i;
- elementsCounter = 1;
- sequence = new StringBuilder();
- sequence.append(numbers[i]);
- }
- }
- if (sequence.length() > 0) {
- if (elementsCounter > longestSeqLength) {
- longestSeqLength = elementsCounter;
- startIndex = indexElements;
- }
- System.out.println(sequence);
- }
- System.out.print("Longest: ");
- for (int i = startIndex; i < startIndex + longestSeqLength; i++) {
- System.out.print(numbers[i]);
- if (i < startIndex + longestSeqLength - 1) {
- System.out.print(" ");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement