Unfortunately this question is quite straightforward; optimal solution is just a for-loop iterating through every contiguous triplet.
code
class Solution {
public:
int countSubarrays(vector<int>& nums) {
int ans = 0;
for (int i = 0; i < nums.size()-2; ++i) {
if (2*(nums[i] + nums[i+2]) == nums[i+1]) {
++ans;
}
}
return ans;
}
};
complexity
- Time:
O(n)wherenis the length of the arraynums- Space:
O(1)
time taken
- 1 minutes and 37 seconds