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

1 Answer

0 votes
/**
 * Finds the consecutive numbers with the largest sum.
 *
 * @param array $numbers Input array of integers.
 * @param int   $windowSize Number of consecutive elements to examine.
 *
 * @return array{
 *     maxSum:int,
 *     numbers:array
 * }
 *
 * @throws InvalidArgumentException
 */
function findMaxSumOfThree(array $numbers, int $windowSize): array
{
    if ($windowSize <= 0) {
        throw new InvalidArgumentException(
            'Window size must be greater than zero.'
        );
    }

    if (count($numbers) < $windowSize) {
        throw new InvalidArgumentException(
            'Array must contain at least windowSize elements.'
        );
    }

    // Calculate the first window sum.
    $currentSum = array_sum(
        array_slice($numbers, 0, $windowSize)
    );

    $maxSum = $currentSum;
    $bestIndex = 0;

    // Slide the window through the array.
    for ($i = $windowSize; $i < count($numbers); $i++) {

        // Add the new value entering the window
        // and remove the value leaving the window.
        $currentSum += $numbers[$i];
        $currentSum -= $numbers[$i - $windowSize];

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

    return [
        'maxSum'  => $maxSum,
        'numbers' => array_slice(
            $numbers,
            $bestIndex,
            $windowSize
        )
    ];
}

// Example usage
$numbers = [4, 2, 0, 8, 7, 5, 1, 3, 9, 6];

$result = findMaxSumOfThree($numbers, 3);

echo 'Largest sum: ' . $result['maxSum'] . PHP_EOL;
echo 'Numbers: ' . implode(' ', $result['numbers']) . PHP_EOL;


/*
run:

Largest sum: 20
Numbers: 8 7 5

*/

 



answered Oct 30 by avibootz

Related questions

...