Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Print triplets with sum less than or equal to k in C Program
Given an array with a set of elements, the task is to find all triplets (sets of exactly three elements) having sum less than or equal to a given value k.
Input − arr[] = {1, 2, 3, 8, 5, 4}, k = 10
Output − triplets → {1, 2, 3} {1, 2, 5} {1, 2, 4} {1, 3, 5} {1, 3, 4} {1, 5, 4} {2, 3, 5} {2, 3, 4}
Syntax
for (i = 0; i < size-2; i++) {
for (j = i+1; j < size-1; j++) {
for (k = j+1; k < size; k++) {
if (arr[i] + arr[j] + arr[k] <= targetSum) {
// Print triplet
}
}
}
}
Algorithm
START
Step 1 → declare int variable sum to k (e.g. 10), i, j, k
Step 2 → declare and initialize size with array size using sizeof(arr)/sizeof(arr[0])
Step 3 → Loop For i to 0 and i<size-2 and i++
Loop For j to i+1 and j<size-1 and j++
Loop For k to j+1 and k<size and k++
IF arr[i] + arr[j] + arr[k] <= sum
Print arr[i] and arr[j] and arr[k]
End IF
End Loop for
End Loop For
Step 4 → End Loop For
STOP
Example
This approach uses three nested loops to generate all possible combinations of three elements and checks if their sum is less than or equal to k −
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 8, 5, 4};
int sum = 10;
int i, j, k;
int size = sizeof(arr)/sizeof(arr[0]);
printf("Triplets with sum <= %d:<br>", sum);
for (i = 0; i < size-2; i++) {
for (j = i+1; j < size-1; j++) {
for (k = j+1; k < size; k++) {
if (arr[i] + arr[j] + arr[k] <= sum) {
printf("{%d, %d, %d}<br>", arr[i], arr[j], arr[k]);
}
}
}
}
return 0;
}
Output
If we run the above program then it will generate the following output −
Triplets with sum <= 10:
{1, 2, 3}
{1, 2, 5}
{1, 2, 4}
{1, 3, 5}
{1, 3, 4}
{1, 5, 4}
{2, 3, 5}
{2, 3, 4}
How It Works
- The algorithm uses three nested loops to generate all possible combinations of three elements.
- The first loop runs from 0 to size-2, second from i+1 to size-1, and third from j+1 to size.
- This ensures we don't pick the same element twice and avoid duplicate combinations.
- Time complexity is O(n³) and space complexity is O(1).
Conclusion
Finding triplets with sum less than or equal to k uses a brute force approach with three nested loops. This method ensures all valid combinations are found without duplicates.
Advertisements
