Java ProgramsRecursionFind Maximum Using Recursion

Find Maximum Using Recursion in Java

beginner·  Recursion  ·  Recursion

Problem

Finding an array's maximum recursively means comparing the current element against the largest value in everything after it, reducing the whole array to a chain of two-way comparisons.

Given an array of integers, find its largest element using recursion.

Input
[12, 45, 7, 23, 56, 3]
Output
Maximum: 56

Java Program

Java
public class FindMaximumRecursion { static int max(int[] arr, int index) { if (index == arr.length - 1) return arr[index]; // last element is its own maximum int restMax = max(arr, index + 1); return Math.max(arr[index], restMax); } public static void main(String[] args) { int[] arr = {12, 45, 7, 23, 56, 3}; System.out.println("Maximum: " + max(arr, 0)); } }

Output

Maximum: 56

Core Logic

Comparing the current element against the maximum of the remaining elements, and keeping whichever is larger, works down to the last element and then unwinds with the running maximum.

How It Works
  1. 1max(arr, index) tracks how far into the array the current call has reached.
  2. 2The base case if (index == arr.length - 1) return arr[index]; fires at the last index, since a single element is trivially its own maximum.
  3. 3Every other call first finds restMax, the maximum of everything after the current index, then returns Math.max(arr[index], restMax).
  4. 4The very first call, max(arr, 0), ends up holding the overall maximum once every deeper call has returned.
For [12, 45, 7, 23, 56, 3], the base case returns 3 at the last index, and each call unwinds comparing its own element against that running maximum — 56 wins as soon as it's compared, and stays the maximum the rest of the way up.
💡

Key Point: Every call needs the deeper call's result before it can decide its own answer — the actual comparison happens entirely on the way back up the call stack, not while descending into it.

Complexity
Time Complexity: O(n)Space Complexity: O(n)

Why: One recursive call handles one array element, so both the call count and the stack depth grow with the array's length n.

Key Concepts

recursionindex parameterbase case

Related Programs