|
| 1 | +import java.util.Scanner; |
| 2 | + |
| 3 | +/** |
| 4 | + * Write a program that reads an array of ints and outputs the length of the longest sequence in strictly ascending order. |
| 5 | + * Print the elements of longest ascending sequence in an array |
| 6 | + * Elements of the sequence must go one after another. A single number is assumed to be an ordered sequence with the length = 1. |
| 7 | + */ |
| 8 | + |
| 9 | +public class longestAscendingSequence { |
| 10 | + |
| 11 | + public static void main(String[] args) { |
| 12 | + |
| 13 | + //Read elements and size |
| 14 | + Scanner scanner = new Scanner(System.in); |
| 15 | + int tam = scanner.nextInt(); |
| 16 | + int[] numbers = new int[tam]; |
| 17 | + |
| 18 | + for (int i = 0; i < numbers.length; i++) { |
| 19 | + numbers[i] = scanner.nextInt(); |
| 20 | + } |
| 21 | + |
| 22 | + //Defining auxiliary variables |
| 23 | + |
| 24 | + int maxTmp = 0; |
| 25 | + int count = 1; |
| 26 | + int pos = -1; |
| 27 | + |
| 28 | + //Traverse the array and increment the amount by 1 the longest amount in the array, in addition to obtaining the position |
| 29 | + for (int i = 0; i < numbers.length - 1; i++) { |
| 30 | + if (numbers[i] < numbers[i + 1]) { |
| 31 | + ++count; |
| 32 | + } else { |
| 33 | + if (count > maxTmp) { |
| 34 | + maxTmp = count; |
| 35 | + pos = i; |
| 36 | + } |
| 37 | + count = 1; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + //Check if count or maxTemp is the highest to assign the position from which the numbers will start printing |
| 42 | + if (maxTmp > count) { |
| 43 | + pos = (pos - maxTmp); |
| 44 | + } |
| 45 | + |
| 46 | + //Get max value |
| 47 | + int max = Math.max(count, maxTmp); |
| 48 | + System.out.println("The max value is : " + max); |
| 49 | + |
| 50 | + //Print elements |
| 51 | + for (int i = pos + 1; i <= pos + max; i++) { |
| 52 | + System.out.print(numbers[i] + " "); |
| 53 | + } |
| 54 | + |
| 55 | + scanner.close(); |
| 56 | + |
| 57 | + |
| 58 | + /* |
| 59 | + Value test |
| 60 | + 10 |
| 61 | + 1 2 4 1 2 3 5 7 4 3 |
| 62 | +
|
| 63 | + 12 |
| 64 | + 1 2 4 1 2 3 5 7 8 9 10 11 |
| 65 | +
|
| 66 | + 20 |
| 67 | + 1 2 4 1 2 3 5 7 4 3 5 8 9 10 12 15 16 2 5 6 |
| 68 | +
|
| 69 | + 15 |
| 70 | + 1 0 2 4 6 3 8 7 0 1 5 8 2 1 3 |
| 71 | +
|
| 72 | + 3 |
| 73 | + 1 2 4 |
| 74 | +
|
| 75 | + 4 |
| 76 | + 1 2 0 0 |
| 77 | +
|
| 78 | + 8 |
| 79 | + 1 2 3 4 5 6 0 3*/ |
| 80 | + |
| 81 | + } |
| 82 | + |
| 83 | +} |
0 commit comments