Skip to content
Advertisement

The maximum value of specific columns of a row java [closed]

I have the following two-dimensional arrays :

1 | 5 | 6 | 16| 8 | 9 | 
9 | 1 | 3 | 4 | 7 | 6 | 
1 | 2 | 4 | 7 | 3 | 8 |

int[][] arr = {{1 ,5 ,6 ,16,8 ,9 }, {9 ,1 ,3 ,4 ,7 ,6 }, {1 ,2 ,4 ,7 ,3 ,8 }};

I need to find the maximum value for a specific row and columns, for example for the 1st row, second and 5th column maximum is 8.

Advertisement

Answer

It is convenient to use Stream API for such purposes:

public static int findMax(int from, int to, int row, int[][] arr) {
    // validate input parameters
    assert 0 <= row && row < arr.length;
    assert 0 <= from && from <= to && to < arr[row].length;

    return Arrays.stream(arr[row])     // IntStream of numbers in the given row
                 .skip(from)           // start `from` column
                 .limit(to - from + 1) // check until `to` column
                 .max()                // pick max value
                 .orElse(Integer.MIN_VALUE); // if max not found (empty array)
}

Test:

int[][] arr = {
    {1, 5, 6, 7, 8, 9 },
    {9, 1, 3, 4, 7, 6},
    {1, 2, 4, 7, 3, 8}
};

System.out.println(findMax(1, 2, 0, arr));

Output:

6

The same may be implemented using common loops:

public static int findMax(int from, int to, int row, int[][] arr) {
    assert 0 <= row && row < arr.length;
    assert 0 <= from && from <= to && to < arr[row].length;

    int max = Integer.MIN_VALUE;
    for (int i = from; i <= to; i++) {
        max = Math.max(max, arr[row][i]);
    }
    return max;
}

Note: in both examples 0-based array indexes are used for row and columns: 1 refers to the 2nd column, 2 refers to the 3rd column, 0 refers to the 1st row.


Update
As it may be needed to look for maximum in a set of columns (not between the two columns inclusively), it may be implemented as:

public static int findMaxInColumns(int[][] arr, int row, int ... cols) {
    assert 0 <= row && row < arr.length;

    return Arrays.stream(cols)
            // optional filter to prevent ArrayOutOfBoundsException
            .filter(col -> col >= 0 && col < arr[row].length)
            .map(col -> arr[row][col])
            .max()
            .orElse(Integer.MIN_VALUE );
}

Test for the same arr:

System.out.println("max in cols 1, 3, 4: " + findMaxInColumns(arr, 0, 1, 3, 4));

Output:

max in cols 1, 3, 4: 8
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement