Oldest Person (Records)

Problem

The input is one line with pairs of a name and an age: name1 age1 name2 age2 ... Print the name and the age of the oldest person. If two persons have the same age, print the one who comes first.

Constraints

  • 1 to 1000 pairs

Examples

Input

Alice 30 Bob 25 Carol 41

Output

Carol 41

Solutions

Best approachTime O(n)Space O(n)

A small class groups two related values. Before Java 16 this needs about 15 lines of boilerplate code.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process one line of text.
 * Input   : One line of text.
 * Output  : Name and age of the oldest person.
 * Approach: Group the data in a class.
 * Time    : O(n)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
        // Step 1: Before records, we write a full class: fields, constructor and getters.
        static class Person {
            private final String name;
            private final int age;

            Person(String name, int age) {
                this.name = name;
                this.age = age;
            }

            String getName() {
                return name;
            }

            int getAge() {
                return age;
            }
        }

    // This method solves the task. It receives the input and returns the answer.
    static String solve(String s) {
        // Step 2: The input has pairs of name and age, separated by spaces.
        String[] tokens = s.trim().split("\\s+");
        Person oldest = null;

        // Step 3: Walk through the pairs. Keep the first person with the largest age.
        for (int i = 0; i < tokens.length; i += 2) {
            Person person = new Person(tokens[i], Integer.parseInt(tokens[i + 1]));
            if (oldest == null || person.getAge() > oldest.getAge()) {
                oldest = person;
            }
        }
        return oldest.getName() + " " + oldest.getAge();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.hasNextLine() ? scanner.nextLine() : "";
        System.out.println(solve(s));
    }
}
Hints (1)
  1. Which person is chosen when two ages are equal?