1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-210/#TASK1
 3 #
 4 # Task 1: Kill and Win
 5 # ====================
 6 #
 7 # You are given a list of integers.
 8 #
 9 # Write a script to get the maximum points. You are allowed to take out (kill)
10 # any integer and remove from the list. However if you do that then all
11 # integers exactly one-less or one-more would also be removed. Find out the
12 # total of integers removed.
13 #
14 ## Example 1
15 ##
16 ## Input: @int = (2, 3, 1)
17 ## Output: 6
18 ##
19 ## First we delete 2 and that would also delete 1 and 3. So the maximum points
20 ## we get is 6.
21 #
22 ## Example 2
23 ##
24 ## Input: @int = (1, 1, 2, 2, 2, 3)
25 ## Output: 11
26 ##
27 ## First we delete 2 and that would also delete both the 1's and the 3. Now we
28 ## have (2, 2).
29 ## Then we delete another 2 and followed by the third deletion of 2. So the
30 ## maximum points we get is 11.
31 #
32 ############################################################
33 ##
34 ## discussion
35 ##
36 ############################################################
37 #
38 # We can check each element from the list as the "kill" integer.
39 # For that integer, we calculate the points.
40 # Then we output the maximum points.
41 
42 use strict;
43 use warnings;
44 use List::Util qw(max);
45 
46 kill_and_win(2, 3, 1);
47 kill_and_win(1, 1, 2, 2, 2, 3);
48 kill_and_win(1, 2, 3, 4, 8, 4, 3);
49 
50 sub kill_and_win {
51    my @list = @_;
52    print "Input: (" . join(", ", @list) . ")\n";
53    my $results;
54    foreach my $elem (@list) {
55       next if $results->{$elem}; # no need to recalculate duplicates
56       # calculate the sum for the deleted elements of the list if we
57       # kill $elem
58       my $result = kill_from_list($elem, @list);
59       $results->{$elem} = $result;
60    }
61    print "Output: " . max(values(%$results)) . "\n";
62 }
63 
64 sub kill_from_list {
65    my ($what, @list) = @_;
66    my $sum = 0;
67    foreach my $elem (@list) {
68       $sum += $elem if $elem == $what;
69       $sum += $elem if $elem == $what + 1;
70       $sum += $elem if $elem == $what - 1;
71    }
72    return $sum;
73 }