3101.交替子数组计数
题目:
解题思路:
动态规划思路,枚举以 i 为末尾下标的交替子数组,统计个数。
class Solution {
public long countAlternatingSubarrays(int[] nums) {
int len = nums.length;
long[] dp = new long[len];
dp[0] = 1;
for (int i = 1; i < len; i++) {
if (nums[i] != nums[i-1]) {
dp[i] = dp[i-1] + 1;
}
else dp[i] = 1;
}
return Arrays.stream(dp).sum();
}
}