Skip to content

Commit 20cc5c0

Browse files
solves #3105: Longest Strictly Increasing or Strictly Decreasing Subarray in java
1 parent a645e7c commit 20cc5c0

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -902,7 +902,7 @@
902902
| 3090 | [Maximum Length Substring With Two Occurrences](https://leetcode.com/problems/maximum-length-substring-with-two-occurrences) | [![Java](assets/java.png)](src/MaximumLengthSubstringWithTwoOccurrences.java) | |
903903
| 3095 | [Shortest Subarray With OR at Least K I](https://leetcode.com/problems/shortest-subarray-with-or-at-least-k-i) | [![Java](assets/java.png)](src/ShortestSubarrayWithORAtLeastKI.java) | |
904904
| 3099 | [Harshad Number](https://leetcode.com/problems/harshad-number) | [![Java](assets/java.png)](src/HarshadNumber.java) | |
905-
| 3105 | [Longest Strictly Increasing or Strictly Decreasing Subarray](https://leetcode.com/problems/longest-strictly-increasing-or-strictly-decreasing-subarray) | | |
905+
| 3105 | [Longest Strictly Increasing or Strictly Decreasing Subarray](https://leetcode.com/problems/longest-strictly-increasing-or-strictly-decreasing-subarray) | [![Java](assets/java.png)](src/LongestStrictlyIncreasingOrStrictlyDecreasingSubarray.java) | |
906906
| 3110 | [Score of a String](https://leetcode.com/problems/score-of-a-string) | | |
907907
| 3114 | [Latest Time You Can Obtain After Replacing Characters](https://leetcode.com/problems/latest-time-you-can-obtain-after-replacing-characters) | | |
908908
| 3120 | [Count the Number of Special Characters I](https://leetcode.com/problems/count-the-number-of-special-characters-i) | | |
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// https://leetcode.com/problems/longest-strictly-increasing-or-strictly-decreasing-subarray
2+
// T: O(N)
3+
// S: O(1)
4+
5+
public class LongestStrictlyIncreasingOrStrictlyDecreasingSubarray {
6+
public int longestMonotonicSubarray(int[] array) {
7+
return Math.max(
8+
lengthLongestIncreasingSubarray(array),
9+
lengthLongestDecreasingSubarray(array)
10+
);
11+
}
12+
13+
private static int lengthLongestIncreasingSubarray(int[] array) {
14+
int length = 1;
15+
for (int i = 1, current = 1 ; i < array.length ; i++) {
16+
if (array[i] > array[i - 1]) {
17+
current++;
18+
} else {
19+
current = 1;
20+
}
21+
length = Math.max(length, current);
22+
}
23+
return length;
24+
}
25+
26+
private static int lengthLongestDecreasingSubarray(int[] array) {
27+
int length = 1;
28+
for (int i = 1, current = 1 ; i < array.length ; i++) {
29+
if (array[i] < array[i - 1]) {
30+
current++;
31+
} else {
32+
current = 1;
33+
}
34+
length = Math.max(length, current);
35+
}
36+
return length;
37+
}
38+
}

0 commit comments

Comments
 (0)