Largest of Three Numbers

beginner Programming Basics

Problem

Read three integers on one line and print the largest one. Some numbers can be equal.

Constraints

  • -10^9 <= each number <= 10^9

Examples

Input

3 9 5

Output

9

Solutions

Best approachTime O(1)Space O(1)

We keep the best number seen so far and compare it with each other number. This idea (keep a maximum) is the base of finding the maximum in an array.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Find the largest of three numbers.
 * Input   : Three integers on one line.
 * Output  : The largest number.
 * Approach: Compare the numbers with if statements.
 * Time    : O(1)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int first = scanner.nextInt();
        int second = scanner.nextInt();
        int third = scanner.nextInt();

        // Step 1: Assume the first number is the largest.
        int largest = first;

        // Step 2: If the second number is larger, it becomes the largest.
        if (second > largest) {
            largest = second;
        }

        // Step 3: If the third number is larger, it becomes the largest.
        if (third > largest) {
            largest = third;
        }

        // Step 4: Print the largest number. Equal numbers work too, because we use > and not >=.
        System.out.println(largest);
    }
}
Hints (1)
  1. Start with one number as the answer. What do you do with each other number?