The longest ascending sequence
# Topic
Iterating over arrays
# Problem
The longest ascending sequence
Write a program that reads an array of ints and outputs the length of the longest sequence in strictly ascending order. Elements of the sequence must go one after another. A single number is assumed to be an ordered sequence with the length = 1.
Input data format
The first line contains the size of an array. The second line contains elements of the array separated by spaces.
Example
The input array is 1 2 4 1 2 3 5 7 4 3
. In this case, the length of the longest sequence in ascending order is 5
. It includes the following elements: 1 2 3 5 7
.
# Solutions
# My solution
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] array = new int[scanner.nextInt()];
int counter = 1;
int maxLength = 1;
for (int i = 0; i < array.length; i++) {
array[i] = scanner.nextInt();
}
for (int i = 0; i < array.length; i++) {
if (i + 1 < array.length) {
if (array[i] < array[i + 1]) {
counter++;
if (maxLength < counter) {
maxLength = counter;
}
} else {
counter = 1;
}
}
}
System.out.println(maxLength);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Other solution
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
int max = 0;
int count = 0;
int before = array[0];
for (int a : array) {
if (before > a) {
if (count > max) {
max = count;
}
count = 0;
}
before = a;
count++;
}
if (count > max) {
max = count;
}
System.out.println(max);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
编辑 (opens new window)
上次更新: 2022/09/25, 10:41:23