How to find the two elements in a list whose sum is closest to zero in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

class ClosestToZero
{
    // Function to find the two elements whose sum is closest to zero
    static void FindClosestToZero(List<int> lst) {
        if (lst.Count < 2) {
            Console.WriteLine("list must have at least two elements.");
            return;
        }

        // Step 1: Sort the list
        List<int> sortedlst = new List<int>(lst);
        sortedlst.Sort();

        int left = 0;
        int right = sortedlst.Count - 1;
        int closestSum = int.MaxValue;
        int[] closestPair = new int[2];

        // Step 2: Use two-indexes technique
        while (left < right) {
            int sum = sortedlst[left] + sortedlst[right];

            // Update closest sum and pair if needed
            if (Math.Abs(sum) < Math.Abs(closestSum)) {
                closestSum = sum;
                closestPair[0] = sortedlst[left];
                closestPair[1] = sortedlst[right];
            }

            // Move indexess
            if (sum < 0) {
                left++; // Increase sum by moving left indexes
            }
            else {
                right--; // Decrease sum by moving right indexes
            }
        }

        // Output the result
        Console.WriteLine("The two elements whose sum is closest to zero are: " +
                          $"{closestPair[0]} and {closestPair[1]} with a sum of {closestSum}.");
    }

    static void Main()
    {
        List<int> lst = new List<int> { 23, -26, -88, -42, 55, 99, -11, 90, -13, 17, -31 };

        FindClosestToZero(lst);
    }
}



/*
run:

The two elements whose sum is closest to zero are: -88 and 90 with a sum of 2.

*/

 



answered Sep 13, 2025 by avibootz
edited Sep 13, 2025 by avibootz
...