Wednesday, November 27, 2013

Find a triplet that sum to a given value

Given an array and a value, find if there is a triplet in array whose sum is equal to the given value. If there is such a triplet present in array, then print the triplet and return true. Else return false. For example, if the given array is {12, 3, 4, 1, 6, 9} and given sum is 24, then there is a triplet (12, 3 and 9) present in array whose sum is 24.

#include
using namespace std;
void display_triplet(int A[],int a_size,int sum)
{
     for(int i=0;i
     {
             int l = i+1;
             int r = a_size - 1;
             while(l
             {
                       if(A[i]+A[l]+A[r] == sum)
                       {
                                         cout<<"["<
                                       //  l++;
                                         r--;
                       }
                       else if(A[i]+A[l]+A[r] < sum)
                       {
                           l++;
                       }
                       else
                       {
                           r--;
                       }
             }
     }
}
int main()
{
    int A[] = {-5,-1,0,2,3,5,9};
    int a_size = sizeof(A)/sizeof(A[0]);
    int sum = 0;
    display_triplet(A,a_size,sum);   
    

}

No comments:

Post a Comment