package sspr1;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadPoolMaxFinder {
    public static int findMax(int[][] matrix, int numThreads) throws InterruptedException, ExecutionException {
        int size = matrix.length;
        ExecutorService executor = Executors.newFixedThreadPool(numThreads);
        Future<Integer>[] futures = new Future[size];

        for (int i = 0; i < size; i++) {
            final int row = i;
            futures[i] = executor.submit(() -> {
                int max = Integer.MIN_VALUE;
                for (int j = row + 1; j < size; j++) {
                    if (matrix[row][j] > max) {
                        max = matrix[row][j];
                    }
                }
                return max;
            });
        }

        int globalMax = Integer.MIN_VALUE;
        for (Future<Integer> future : futures) {
            int localMax = future.get();
            if (localMax > globalMax) {
                globalMax = localMax;
            }
        }

        executor.shutdown();
        return globalMax;
    }
}
