The weekly challenge 289 - Task 1: Third Maximum

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-289/#TASK1
 3 #
 4 # Task 1: Third Maximum
 5 # =====================
 6 #
 7 # You are given an array of integers, @ints.
 8 #
 9 # Write a script to find the third distinct maximum in the given array. If
10 # third maximum doesn’t exist then return the maximum number.
11 #
12 ## Example 1
13 ##
14 ## Input: @ints = (5, 6, 4, 1)
15 ## Output: 4
16 ##
17 ## The first distinct maximum is 6.
18 ## The second distinct maximum is 5.
19 ## The third distinct maximum is 4.
20 #
21 ## Example 2
22 ##
23 ## Input: @ints = (4, 5)
24 ## Output: 5
25 ##
26 ## In the given array, the third maximum doesn't exist therefore returns the maximum.
27 #
28 ## Example 3
29 ##
30 ## Input: @ints =  (1, 2, 2, 3)
31 ## Output: 1
32 ##
33 ## The first distinct maximum is 3.
34 ## The second distinct maximum is 2.
35 ## The third distinct maximum is 1.
36 #
37 ############################################################
38 ##
39 ## discussion
40 ##
41 ############################################################
42 #
43 # We collect all distinct numbers as keys in a hash table. Then we
44 # sort these by size. In the end we keep the third maximum, if it
45 # is defined, otherwise the maximum.
46 
47 use strict;
48 use warnings;
49 
50 third_maximum(5, 6, 4, 1);
51 third_maximum(4, 5);
52 third_maximum(1, 2, 2, 3);
53 
54 sub third_maximum {
55    my @ints = @_;
56    print "Input: (" . join(", ", @ints) . ")\n";
57    my $seen;
58    map { $seen->{$_} = 1; } @ints;
59    my @sorted_keys = sort { $b <=> $a } keys %$seen;
60    my $result = $sorted_keys[2] // $sorted_keys[0];
61    print "Output: $result\n";
62 }