Skip to content

Commit 4f9f93c

Browse files
committed
feat(leetcode): add No.2765
1 parent 98438fe commit 4f9f93c

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// https://leetcode.com/problems/longest-alternating-subarray/
2+
// algorithms
3+
// Easy (32.6%)
4+
// Total Accepted: 14.9K
5+
// Total Submissions: 45.6K
6+
7+
class Solution {
8+
9+
public int alternatingSubarray(int[] nums) {
10+
int len = nums.length;
11+
if (len < 2) {
12+
return -1;
13+
}
14+
15+
int diff = 1;
16+
int curSubArrLen = 1;
17+
int res = -1;
18+
for (int i = 1; i < len; i++) {
19+
if (nums[i] - nums[i - 1] == diff) {
20+
curSubArrLen++;
21+
diff = -diff;
22+
} else if (curSubArrLen > 1) {
23+
res = Math.max(res, curSubArrLen);
24+
25+
if (nums[i] - nums[i - 1] == -diff) {
26+
curSubArrLen = 2;
27+
} else {
28+
curSubArrLen = 1;
29+
diff = 1;
30+
}
31+
}
32+
}
33+
34+
if (curSubArrLen > 1) {
35+
res = Math.max(res, curSubArrLen);
36+
}
37+
38+
return res;
39+
}
40+
41+
}
42+
43+
// [14,30,29,49,3,23,44,21,26,52]

0 commit comments

Comments
 (0)