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

1 Answer

0 votes
public class MaxThreeConsecutiveSum {

    /**
     * Stores the result of the search.
     */
    public static class Result {
        private final int startIndex;
        private final int maxSum;

        public Result(int startIndex, int maxSum) {
            this.startIndex = startIndex;
            this.maxSum = maxSum;
        }

        public int getStartIndex() {
            return startIndex;
        }

        public int getMaxSum() {
            return maxSum;
        }
    }

    /**
     * Finds three consecutive numbers with the largest sum.
     *
     * @param numbers Input array
     * @return Result containing:
     *         - start index of the best sequence
     *         - largest sum found
     * @throws IllegalArgumentException if the array has fewer than 3 elements
     */
    public static Result findMaxSumOfThree(int[] numbers, int total) {

        if (numbers == null || numbers.length < total) {
            throw new IllegalArgumentException(
                "Array must contain at least " + total + " elements."
            );
        }

        // Sum of the first window
        int currentSum = numbers[0] + numbers[1] + numbers[2];
        int maxSum = currentSum;
        int bestIndex = 0;

        // Slide the window across the array
        for (int i = 3; i < numbers.length; i++) {

            // Add new element and remove old element
            currentSum += numbers[i];
            currentSum -= numbers[i - total];

            if (currentSum > maxSum) {
                maxSum = currentSum;
                bestIndex = i - 2;
            }
        }

        return new Result(bestIndex, maxSum);
    }

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 8, 3, 9};

        Result result = findMaxSumOfThree(numbers, 3);

        System.out.println("Largest sum: " + result.getMaxSum());

        System.out.println(
            "Numbers: "
            + numbers[result.getStartIndex()] + " "
            + numbers[result.getStartIndex() + 1] + " "
            + numbers[result.getStartIndex() + 2]
        );
    }
}


/*
run:

Largest sum: 20
Numbers: 8 3 9

*/

 



answered Oct 29 by avibootz

Related questions

...