Answer the question
In order to leave comments, you need to log in
How to find the largest increasing slice of an array?
There is a task:
Find the largest increasing slice of the array.
A slice is a sequence of consecutive array elements, where each next element is greater than the previous one.
For the sequence 1 2 3 1 2 5 7 1 2 1 2, there are increasing slices: 1 2 3, 1 2 5 7, 1 2, 1 2 you need to output the slice 1 2 5 7
For the sequence 1 2 3 1 2 5 1 2 7 , there are slices 1 2 3, 1 2 5, 1 2 7 you need to output all the slices, since they are of equal length
Input data format:
Given a natural number N, followed by N integers.
Output data format:
On the first line print the length of the maximum slice
Next print the content of the slice/slices, separating the elements with a single space, each slice on a new line
Sample Input 1:
7
2 1 2 3 1 5 7
Sample Output 1:
3
1 2 3
1 5 7
Sample Input 2:
5
1 2 3 4 5
Sample Output 2:
5
1 2 3 4 5
Sample Input 3:
7
1 2 1 5 1 7 1
Sample Output 3:
2
1 2
1 5
1 7
Question: can I finish my code, or am I moving in the wrong direction? Point to the right path! Is it possible to solve without the second array?
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = in.nextInt();
}
int count = 0;
int count2 = 0;
for (int i = 0; i < array.length - 1; i++) {
if (array[i] < array[i + 1]) {
count++;
}
if (array[i] > array[i + 1]) {
count++;
count2 = count;
count = 0;
}
}
int length = Math.max(count + 1, count2);
System.out.println(length);
int count3 = 0;
for (int i = 1; i < array.length; i++) {
if (array[i] < array[i - 1]) {
System.out.print(array[i] + " ");
}
if (array[i] > array[i - 1]) {
System.out.print(array[i] + " ");
count3++;
}
if (count3 == length - 1) {
System.out.println();
count3 = 0;
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question