LeetCode - Algorithms - 896. Monotonic Array

Problem

896. Monotonic Array

Java

One Pass

© Approach 3: One Pass (Simple Variant)

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public boolean isMonotonic(int[] A) {
boolean increasing = true;
boolean decreasing = true;
for (int i = 0; i < A.length - 1; i++) {
if (A[i] > A[i + 1]) decreasing = false;
if (A[i] < A[i + 1]) increasing = false;
}
return increasing || decreasing;
}
}

Submission Detail

  • 366 / 366 test cases passed.
  • Runtime: 1 ms, faster than 100.00% of Java online submissions for Monotonic Array.
  • Memory Usage: 47.8 MB, less than 18.59% of Java online submissions for Monotonic Array.

my solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public boolean isMonotonic(int[] A) {
final int N = A.length;
if (N<=2)
return true;
int[] d = new int[N-1];
for(int i=1, j=0; i<N; i++,j++) {
d[j] = A[i]-A[i-1];
}
int min=d[0],max=d[0];
for(int i=1; i<N-1; i++) {
if (d[i]<min) min = d[i];
if (d[i]>max) max = d[i];
}
return (min<=0 && max<=0) || (min>=0 && max>=0);
}
}

Submission Detail

  • 366 / 366 test cases passed.
  • Runtime: 2 ms, faster than 31.40% of Java online submissions for Monotonic Array.
  • Memory Usage: 46.9 MB, less than 18.59% of Java online submissions for Monotonic Array.