00:00

Problem Statement

Input/Output Examples

Visual Explanation

Every element is compared with the current max exactly once. Starting from arr[0] instead of 0 is what makes the method correct for arrays in which every value is negative.

Approaches

Both approaches visit each element once. One writes the loop by hand; the other uses IntStream.max().

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the number of elements. Each element is compared once, and only one extra variable is needed, so both approaches use O(1) auxiliary space.

Interview Tips and Recommended Approach

  • Do not start with max = 0. For [-8, -3, -15] it would return 0, which is not even in the array.
  • Say what happens for an empty array. Throwing an exception, returning Integer.MIN_VALUE or returning an OptionalInt are all valid, but you must choose one.
  • Avoid sorting. Arrays.sort() followed by the last element works, but it costs O(n log n) and changes the input.
  • Know the follow-ups: the smallest element, the second largest and the index of the maximum all use the same single-pass idea.

Recommended Approach: Single Loop

Why: it reads the array once, needs no extra memory and handles negative numbers because it starts from a real element. Every step is visible, which is what an interviewer wants to see.