Maximum Subarray Sum in Linear and Circular Arrays

This solution computes the maximum contiguous subarray sum for integer arrays in both linear and circular configurations. The program reads integer values from a file, handles large numbers and input errors gracefully, and implements efficient algorithms for both array types.

Non-Circular Array Algorithm

For linear arrays, we traverse the array while maintaining the maximum subarray sum ending at each position. The algorithm updates each element to reflect the maximum sum achievable at that position by either starting a new subarray or extending the previous one:

int current = array[0];
int globalMax = array[0];
for (int i = 1; i < array.length; i++) {
    current = Math.max(array[i], current + array[i]);
    globalMax = Math.max(globalMax, current);
}
return globalMax;

Circular Array Algorithm

For circular arays, we use an efficient approach that considers two scenarios: the maximum subarray appears in the linear portion, or it wraps around the array boundary. The solution combines the total array sum with the minimum subarray sum:

int linearMax = computeLinearMax(array);
if (linearMax < 0) return linearMax; // All negative case

int total = 0;
for (int num : array) total += num;

int currentMin = array[0];
int globalMin = array[0];
for (int i = 1; i < array.length; i++) {
    currentMin = Math.min(array[i], currentMin + array[i]);
    globalMin = Math.min(globalMin, currentMin);
}

int circularMax = total - globalMin;
return Math.max(linearMax, circularMax);

File Handling and Validation

The implementation includes robust file reading and integer validasion using regular expressions to ensure only valid integers are processed:

private static int[] readData(String filename) throws IOException, DataException {
    List<integer> values = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
        String line;
        while ((line = reader.readLine()) != null) {
            String[] tokens = line.split("\\s+");
            for (String token : tokens) {
                if (!token.matches("-?\\d+")) {
                    throw new DataException("Invalid integer: " + token);
                }
                values.add(Integer.parseInt(token));
            }
        }
    }
    return values.stream().mapToInt(i -> i).toArray();
}

static class DataException extends Exception {
    public DataException(String message) {
        super(message);
    }
}</integer>

Complete Implementation

public class SubarraySumCalculator {
    static class DataException extends Exception {
        public DataException(String message) {
            super(message);
        }
    }

    public static void main(String[] args) {
        if (args.length == 0) {
            System.err.println("Missing filename argument");
            return;
        }

        try {
            int[] data = readData(args[0]);
            int linearMax = computeLinearMax(data);
            int circularMax = computeCircularMax(data);
            System.out.println("Linear maximum: " + linearMax);
            System.out.println("Circular maximum: " + circularMax);
        } catch (IOException | DataException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }

    private static int computeLinearMax(int[] array) {
        int current = array[0];
        int globalMax = array[0];
        for (int i = 1; i < array.length; i++) {
            current = Math.max(array[i], current + array[i]);
            globalMax = Math.max(globalMax, current);
        }
        return globalMax;
    }

    private static int computeCircularMax(int[] array) {
        int linearMax = computeLinearMax(array);
        if (linearMax < 0) return linearMax;

        int total = 0;
        for (int num : array) total += num;

        int currentMin = array[0];
        int globalMin = array[0];
        for (int i = 1; i < array.length; i++) {
            currentMin = Math.min(array[i], currentMin + array[i]);
            globalMin = Math.min(globalMin, currentMin);
        }

        return Math.max(linearMax, total - globalMin);
    }

    private static int[] readData(String filename) throws IOException, DataException {
        // Implementation as shown above
    }
}

Tags: java Subarray Sum Kadane Algorithm Circular Array file processing

Posted on Fri, 21 Aug 2026 16:33:14 +0000 by Clarkey Boy