ให้อาเรย์ หาจำนวนกลุ่มขนาด 2 และ 3 ที่ผลรวมหาร 3 ลงตัว
ตัวอย่าง:
Input: arr = [1, 2, 3, 4] Output: 4
กลุ่ม: [1,2], [2,4], [1,2,3], [2,3,4]
อัลกอริทึม
- count = 0
- 2 loops หาคู่ขนาด 2: ถ้า sum % 3 == 0 count++
- 3 loops หาคู่ขนาด 3: ถ้า sum % 3 == 0 count++
- คืนค่า count
การเขียนโปรแกรม C++
#include <bits/stdc++.h> using namespace std; int getNumberOfGroupsDivisibleBy3(int arr[], int n) { int count = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if ((arr[i] + arr[j]) % 3 == 0) count++; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) if ((arr[i] + arr[j] + arr[k]) % 3 == 0) count++; return count; } int main() { int arr[] = { 2, 3, 4, 5, 6, 1, 2, 4, 7, 8 }; int n = 10; cout << getNumberOfGroupsDivisibleBy3(arr, n) << endl; return 0; }
ผลลัพธ์
57