ได้รับอาร์เรย์จำนวนเต็ม Arr[] และช่วง [a, b] ต้องการนับทริปเล็ต (i อินพุต: arr[] = {1, 2, 3, 4, 5}, N = 5, L = 2, R = 8 เอาต์พุต: 4 คำอธิบาย: (1,2,3)=6, (1,2,4)=7, (1,2,5)=8, (1,3,4)=8 อินพุต: arr[] = {2, 2, 2, 2, 2}, N = 5, L = 2, R = 5 เอาต์พุต: 0 (ผลรวมทุกทริปเล็ต = 6 ไม่อยู่ในช่วง)ตัวอย่าง
แนวทาง
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
int countTriplets(int arr[], int n, int a, int b) {
int count = 0, sum = 0;
for (int i = 0; i < n-2; i++) {
for (int j = i+1; j < n-1; j++) {
for (int k = j+1; k < n; k++) {
sum = arr[i] + arr[j] + arr[k];
if (sum >= a && sum <= b) count++;
}
}
}
return count;
}
int main() {
int Arr[] = {5, 4, 3, 6, 8, 2};
int L = 9, R = 15, N = 6;
cout << endl << "Number of triplets: " << countTriplets(Arr, N, L, R);
return 0;
}
ผลลัพธ์
Number of triplets: 14