짬뽕얼큰하게의 맨땅에 헤딩 :: '2025/04/14 글 목록

'2025/04/14'에 해당되는 글 1건

Count Good Triplets

알고리즘 2025. 4. 14. 21:03

Leetcode Problem:

Summary

  • Find the number of good triplets in an array of integers given three integers a, b, and c.

Approach

  • Three nested loops are used to iterate through the array and check each triplet against the conditions
  • The absolute difference between each pair of numbers is calculated and compared to the given integers a, b, and c
  • If all conditions are met, the triplet is counted.

Complexity

  • O(n^3) where n is the size of the array

Explanation

  • The solution uses three nested loops to iterate through the array
  • The outer loop starts at the first element, the middle loop starts at the next element after the outer loop, and the inner loop starts at the next element after the middle loop
  • The solution checks each triplet against the conditions and increments the count if all conditions are met.

Solution Code:


class Solution {
public:
    
    int countGoodTriplets(vector& arr, int a, int b, int c) {
        int ans = 0;
        for(int i = 0 ; i < arr.size(); i++){
            for(int j = i + 1; j < arr.size(); j++){
                for(int k = j + 1; k < arr.size(); k++){
                    if(abs(arr[i] - arr[j]) <= a &&
                       abs(arr[j] - arr[k]) <= b &&
                       abs(arr[k] - arr[i]) <= c){
                        ans++;
                       }
                }

            }
        }
        return ans;
    }
};

'알고리즘' 카테고리의 다른 글

Count the Number of Good Subarrays  (0) 2025.04.17
Count Good Triplets in an Array  (0) 2025.04.15
Count Good Numbers  (0) 2025.04.13
Find the Count of Good Integers  (1) 2025.04.12
Count Symmetric Integers  (0) 2025.04.11
블로그 이미지

짬뽕얼큰하게

,