-1

How do I find the maximum number of all the dp[1] values? In this example below, answer is 21, as I only look at the second number of the set. Currently using a for loop, but looking for something efficient.

int[][] dp = new int[30][2];

{5,9}, {31,7}, {4, 21}, {24, 16}

This question is slightly different Java- Finding maximum number in a 2D array

2
  • correct @Abra 9,7,21,16 Commented Jun 24, 2023 at 5:17
  • A for loop should be super efficient, though perhaps a bit more verbose (and less potentially parallelizable) than other approaches. For instance, you're unlikely to find a solution that's more efficient than int max = Integer.MIN_VALUE; for (int[] arr : dp) { max = Math.max(arr[1], max); } Commented Jun 24, 2023 at 5:27

1 Answer 1

2

This can be solved in a straightforward manner using streams:

int[][] dp = {{5,9}, {6,7}, {4, 21}, {7, 12}};

int max = Arrays.stream(dp).mapToInt(a -> a[1]).max().orElseThrow();

This streams over the outer array, maps each inner array to the second element of that array, then returns the maximum element of those mapped values.

Detailed breakdown

  1. Arrays.stream(dp) - Returns a Stream<int[]> of the array's elements.
  2. mapToInt(a -> a[1]) - Applies a ToIntFunction<int[]> to each element of the Stream<int[]>, returning an IntStream of those results. This uses function a -> a[1], which takes an array and returns the element at index 1.
  3. max() - Returns the maximum int in the IntStream as an OptionalInt. This OptionalInt will contain the max value (unless the stream is empty, in which case it'll be an empty OptionalInt).
  4. orElseThrow - Returns the int value in the OptionalInt, or throws NoSuchElementException if the OptionalInt is empty.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.