-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMonotonicArray.java
59 lines (45 loc) · 1.12 KB
/
MonotonicArray.java
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.leetcode.algorithms.easy.array;
import java.util.Scanner;
import com.leetcode.util.InputUtil;
public class MonotonicArray {
public static void main(String...strings) {
// Input
Scanner scanner = new Scanner(System.in);
String[] inputs = InputUtil.inputArr(scanner.next());
int[] A = InputUtil.integerArr(inputs);
// Check if array is monotonic
System.out.println(isMonotonic(A));
scanner.close();
}
public static boolean isMonotonic(int[] A) {
if(A.length == 0) {
return true;
} else {
if(A.length == 1) {
return true;
} else {
int countMonotonicOrder = 0;
// Check for ascending order
for(int i = 0; i < A.length - 1; i++) {
if(A[i + 1] >= A[i]) {
++countMonotonicOrder;
}
}
if(countMonotonicOrder == A.length - 1) {
return true;
}
countMonotonicOrder = 0;
// Check for descending order
for(int i = 1; i < A.length; i++) {
if(A[i - 1] >= A[i]) {
++countMonotonicOrder;
}
}
if(countMonotonicOrder == A.length - 1) {
return true;
}
return false;
}
}
}
}