Wednesday 21 August 2024

Pair with given Sum (Two Sum)

 Given an array A[] of n numbers and another number x, the task is to check whether or not there exist two elements in A[] whose sum is exactly x. 

Examples: 

Input: arr[] = {0, -1, 2, -3, 1}, x= -2
Output: Yes
Explanation: If we calculate the sum of the output,1 + (-3) = -2

Input: arr[] = {1, -2, 1, 0, 5}, x = 0
Output: No




int[] intArr = {1,2,3,4,5,6,7,8,9};

Dictionary<int,int> keyValues1 = new Dictionary<int,int>();


//iterate 0 lenght-1 ,

//take 1

bool isSumMatch = false;

int target = 15;


for(int i=0;i<intArr.Length;i++)

{

    for(int j=i;j<intArr.Length-1;j++)

    {

        if (target == (intArr[i] + intArr[j + 1]))

        {

            isSumMatch = true;

           keyValues1.Add(intArr[i], i);

            keyValues1.Add(intArr[j+1], j+1);

            break;

        }


        if ((intArr[i] + intArr[j + 1]) > target)

            break;

    }


    if (isSumMatch)

        break;

}


foreach(var d in keyValues1)

{

    Console.WriteLine(d.Key +" " + d.Value);

No comments:

Post a Comment