Find Triplet with Given Sum
C++
Hard
9 views
Problem Description
Find three numbers in array whose sum equals target value.This develops nested loop optimization and multiple variable tracking.
Logic: Use three nested loops to check all possible combinations
Official Solution
void question13_triplet_sum() {
int arr[] = {1, 4, 45, 6, 10, 8};
int size = 6;
int target = 22;
bool found = false;
for(int i = 0; i < size - 2; i++) {
for(int j = i + 1; j < size - 1; j++) {
for(int k = j + 1; k < size; k++) {
if(arr[i] + arr[j] + arr[k] == target) {
cout << "Triplet: " << arr[i] << ", " << arr[j]
<< ", " << arr[k] << endl;
found = true;
break;
}
}
if(found) break;
}
if(found) break;
}
if(!found) cout << "No triplet found" << endl;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!