Pair products,
peak points
Weekly challenge 339 — 15 September 2025
Week 339: 15 Sep 2025
You are given an array of altitude gain. Write a script to find the peak point gained.
Example 1 Input: @gain = (-5, 1, 5, -9, 2) Output: 1 start: 0 1st change: 0 + (-5) = -5 2nd change: -5 + 1 = -4 3rd change: -4 + 5 = 1 4th change: 1 + (-9) = -8 5th change: -8 + 2 = -6 max(0, -5, -4, 1, -8, -6) = 1 Example 2 Input: @gain = (10, 10, 10, -25) Output: 30 Example 3 Input: @gain = (3, -4, 2, 5, -6, 1) Output: 6 Example 4 Input: @gain = (-1, -2, -3, -4) Output: 0 Example 5 Input: @gain = (-10, 15, 5) Output: 10
This is another task which can probably be reduced to a one-liner, but I have done it more transparently by repeatedly adding (or subtracting) the steps from a starting point of zero.
This is related to the statistical problem known as the drunkard's walk.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2025-09-15 use utf8; # Week 339 - task 2 - Peak point use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; peak_point(-5, 1, 5, -9, 2); peak_point(10, 10, 10, -25); peak_point(3, -4, 2, 5, -6, 1); peak_point(-1, -2, -3, -4); peak_point(-10, 15, 5); my @steps; push @steps, int(rand(21)) - 10 for 1 .. 100; peak_point(@steps); sub peak_point { my ($height, $highest, $climb); # initialise $height = 0; $highest = 0; # start climbing for $climb (@_) { $height += $climb; $highest = $height if $height > $highest; } say qq[\nInput: (] . join(', ', @_) . ')'; say qq[Output: $highest]; }
Input: (-5, 1, 5, -9, 2) Output: 1 Input: (10, 10, 10, -25) Output: 30 Input: (3, -4, 2, 5, -6, 1) Output: 6 Input: (-1, -2, -3, -4) Output: 0 Input: (-10, 15, 5) Output: 10 Input: (7, 10, -5, 6, 8, -7, 5, -7, 1, -3, -10, 2, 2, -4, -3, -2, -9, -4, 8, -5, 10, -10, -6, 5, -1, -8, -8, 1, -5, -5, -8, -5, -2, 8, -8, -2, -2, 3, -9, -9, -8, -3, 6, -4, -6, -7, 8, 4, 6, -1, -8, 6, 7, -1, -2, 7, -1, 1, -6, -3, 6, -4, -3, -2, -6, -6, 8, 1, -4, 1, -5, 0, 6, 2, 4, 5, 1, -7, -9, -7, -3, -3, 10, 3, 7, 0, 7, -8, -1, -1, 5, -4, -8, 10, -1, -3, -6, 9, -10, 8) Output: 26
Any content of this website which has been created by Peter Campbell Smith is in the public domain