Skip to content

Commit

Permalink
feat(leetcode): add No.2765
Browse files Browse the repository at this point in the history
  • Loading branch information
mickey0524 committed Jul 17, 2023
1 parent 98438fe commit 4f9f93c
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions 2765.Longest-Alternating-Subarray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// https://leetcode.com/problems/longest-alternating-subarray/
// algorithms
// Easy (32.6%)
// Total Accepted: 14.9K
// Total Submissions: 45.6K

class Solution {

public int alternatingSubarray(int[] nums) {
int len = nums.length;
if (len < 2) {
return -1;
}

int diff = 1;
int curSubArrLen = 1;
int res = -1;
for (int i = 1; i < len; i++) {
if (nums[i] - nums[i - 1] == diff) {
curSubArrLen++;
diff = -diff;
} else if (curSubArrLen > 1) {
res = Math.max(res, curSubArrLen);

if (nums[i] - nums[i - 1] == -diff) {
curSubArrLen = 2;
} else {
curSubArrLen = 1;
diff = 1;
}
}
}

if (curSubArrLen > 1) {
res = Math.max(res, curSubArrLen);
}

return res;
}

}

// [14,30,29,49,3,23,44,21,26,52]

0 comments on commit 4f9f93c

Please sign in to comment.