Thursday 3 February 2022

C# program to determine if any two integers in array sum to given integer

 

In this article, we will learn how to determine if two integers in array sum to given integer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodingAlgorithm
{
    //Given an integer and an array of integers determine whether any two integers in the array sum to that integer.
    public static class TargetSum
    {
        //Brute force solution, O(n^2) time complexity
        public static bool TwoIntegersSumToTarget(int[] arr, int target)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                for (int k = 0; k < arr.Length; k++)
                {
                    if (i != k)
                    {
                        int sum = arr[i] + arr[k];
                        if (sum == target)
                            return true;
                    }
                }
            }
            return false;
        }
    }
}

No comments:

Post a Comment