package sspr1;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class ForkJoinMaxFinder {
    private static class MaxFinderTask extends RecursiveTask<Integer> {
        private final int[][] matrix;
        private final int startRow;
        private final int endRow;

        public MaxFinderTask(int[][] matrix, int startRow, int endRow) {
            this.matrix = matrix;
            this.startRow = startRow;
            this.endRow = endRow;
        }

        @Override
        protected Integer compute() {
            if (endRow - startRow <= 1) {
                int max = Integer.MIN_VALUE;
                for (int j = startRow + 1; j < matrix.length; j++) {
                    if (matrix[startRow][j] > max) {
                        max = matrix[startRow][j];
                    }
                }
                return max;
            } else {
                int mid = (startRow + endRow) / 2;
                MaxFinderTask leftTask = new MaxFinderTask(matrix, startRow, mid);
                MaxFinderTask rightTask = new MaxFinderTask(matrix, mid, endRow);
                leftTask.fork();
                int rightResult = rightTask.compute();
                int leftResult = leftTask.join();
                return Math.max(leftResult, rightResult);
            }
        }
    }

    public static int findMax(int[][] matrix) {
        ForkJoinPool pool = new ForkJoinPool();
        return pool.invoke(new MaxFinderTask(matrix, 0, matrix.length));
    }
}
