알고리즘

Count Subarrays of Length Three With a Condition

짬뽕얼큰하게 2025. 4. 27. 09:30

Leetcode Problem:

Summary

  • Given an integer array, return the number of subarrays of length 3 such that the sum of the first and third numbers equals exactly half of the second number.

Approach

  • The approach used is to iterate over the array with three nested loops, but with a slight modification
  • Instead of using three nested loops, we use two nested loops and check for the third element
  • We then check if the sum of the first and third elements equals half of the second element, and if so, we increment the count.

Complexity

  • O(n^2)

Explanation

  • The solution iterates over the array with two nested loops, where the outer loop iterates over the first element and the inner loop iterates over the third element
  • For each pair of elements, it checks if the sum of the first and third elements equals half of the second element
  • If so, it increments the count
  • The time complexity is O(n^2) because in the worst case, we need to check all pairs of elements.

Solution Code:


class Solution {
public:
    int countSubarrays(vector& nums) {
        int ans = 0;
        for(int i = 0 ; i < nums.size() - 2; i++){
            if((nums[i] + nums[i+2])*2 == nums[i+1]){
                ans++;
            }
        }
        return ans;
    }
};