How to find three consecutive numbers with the largest sum in an array of integers in C#

1 Answer

0 votes
using System;

public class Result
{
    public int MaxSum { get; set; }
    public int[] Numbers { get; set; } = Array.Empty<int>();
}

public static class ArrayHelper
{
    /// <summary>
    /// Finds the consecutive numbers with the largest sum.
    /// </summary>
    /// <param name="numbers">Input array.</param>
    /// <param name="windowSize">
    /// Number of consecutive elements to examine.
    /// </param>
    /// <returns>
    /// A Result object containing:
    /// - MaxSum: the largest sum found
    /// - Numbers: the matching consecutive numbers
    /// </returns>
    public static Result FindMaxSumOfThree(
        int[] numbers,
        int windowSize)
    {
        if (numbers == null)
            throw new ArgumentNullException(nameof(numbers));

        if (windowSize <= 0)
            throw new ArgumentOutOfRangeException(nameof(windowSize));

        if (numbers.Length < windowSize) {
            throw new ArgumentException(
                "Array must contain at least windowSize elements.");
        }

        // Calculate the first window sum.
        int currentSum = 0;

        for (int i = 0; i < windowSize; i++) {
            currentSum += numbers[i];
        }

        int maxSum = currentSum;
        int bestIndex = 0;

        // Slide the window through the array.
        for (int i = windowSize; i < numbers.Length; i++)
        {
            // Add the new element entering the window.
            currentSum += numbers[i];

            // Remove the element leaving the window.
            currentSum -= numbers[i - windowSize];

            if (currentSum > maxSum) {
                maxSum = currentSum;
                bestIndex = i - windowSize + 1;
            }
        }

        int[] bestNumbers = new int[windowSize];

        Array.Copy(
            numbers,
            bestIndex,
            bestNumbers,
            0,
            windowSize);

        return new Result
        {
            MaxSum = maxSum,
            Numbers = bestNumbers
        };
    }
}

class Program
{
    static void Main()
    {
        int[] numbers =
        {
            4, 2, 0, 8, 7, 5, 1, 3, 9, 6
        };

        Result result = ArrayHelper.FindMaxSumOfThree(numbers, 3);

        Console.WriteLine($"Largest sum: {result.MaxSum}");
        Console.WriteLine($"Numbers: {string.Join(" ", result.Numbers)}");
    }
}


/*
run:

Largest sum: 20
Numbers: 8 7 5

*/

 



answered Oct 30 by avibootz

Related questions

...