The Weekly Challenge - 289

TASK #1: Third Maximum
You are given an array of integers, @ints.

Write a script to find the third distinct maximum in the given array. If third maximum doesn’t exist then return the maximum number.

#!/usr/bin/perl
use strict;
use warnings;

sub third_maximum {

    # remove duplicates: see example 3 and 4
    my @unique = keys %{{ map { $_ => 1 } @_ }};
    
    # sort numerically
    @unique = sort { $a <=> $b } @unique;
    
    # return the third largest or the largest if fewer than 3 elements
    return (scalar(@unique) >= 3) ? $unique[-3] : $unique[-1];
}

# Tests
my @ints;

Example 1
@ints = (5, 6, 4, 1);
print(third_maximum(@ints), "\n"); # Output 4

Example 2
@ints = (4, 5);
print(third_maximum(@ints), "\n"); # Output: 5

Example 3
@ints =  (1, 2, 2, 3);
print(third_maximum(@ints), "\n"); # Output: 1

Example 4
@ints =  (3, 3, 3, 3, 2, 2, 2, 1);
print(third_maximum(@ints), "\n"); # Output: 1