Find the Largest of Three Numbers

Solve this Problem
Easy5–10 min
Topics
Companies
Given three integers a, b, and c, return the largest of the three. If more than one share the largest value, any of them is a correct answer. The nested if-elseNested If-ElseCombining two comparisons with && inside each branch of an if/else-if/else chain. version checks all three candidates explicitly, one at a time. The running maximumRunning MaximumKeeping a single "best so far" value and updating it by comparing against one new value at a time, instead of comparing everything against everything at once. version never compares three things simultaneously — it reduces the problem to two simple two-value comparisons, which is exactly the technique used to find the largest value in an array of any length.

Test Case 1:

Input:a = 4, b = 9, c = 2
Output:9
Explanation:9 is greater than both 4 and 2.

Test Case 2:

Input:a = 3, b = 8, c = 5
Output:8
Explanation:8 is greater than both 3 and 5.

Test Case 3:

Input:a = 5, b = 5, c = 5
Output:5
Explanation:All three are equal — any of them is correct.

Constraints

  • ◆-1000 ≤ a ≤ 1000
  • ◆-1000 ≤ b ≤ 1000
  • ◆-1000 ≤ c ≤ 1000

Try the Dry Run

Approach & Solutions

Nested If-ElseGood

Check each candidate in turn: a is the answer if it's greater than or equal to both b and c; otherwise b is the answer if it beats both a and c; otherwise c must be the largest by elimination. Three outcomes, decided with two comparisons joined by AND at each step.

TimeO(1)
SpaceO(1)
1class Solution { 2 public int findLargestOfThree(int a, int b, int c) { 3 if (a >= b && a >= c) { 4 return a; 5 } else if (b >= a && b >= c) { 6 return b; 7 } else { 8 return c; 9 } 10 } 11}
Running Maximum — Compare Two at a TimeOptimal

Never compare three things at once — reduce it to two comparisons between two values each. First find the larger of a and b and keep it as a running max; then compare that running max against c. Whatever survives both rounds is the overall largest. This is the same one-pass-maximum idea used for finding the largest element in an array of any size, just unrolled for exactly three values.

TimeO(1)
SpaceO(1)
1class Solution { 2 public int findLargestOfThree(int a, int b, int c) { 3 int max = (a > b) ? a : b; 4 max = (max > c) ? max : c; 5 return max; 6 } 7}

Related Problems