The weekly challenge 302 - Task 2: Step by Step
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-302/#TASK2 3 # 4 # Task 2: Step by Step 5 # ==================== 6 # 7 # You are given an array of integers, @ints. 8 # 9 # Write a script to find the minimum positive start value such that step by 10 # step sum is never less than one. 11 # 12 ## Example 1 13 ## 14 ## Input: @ints = (-3, 2, -3, 4, 2) 15 ## Output: 5 16 ## 17 ## For start value 5. 18 ## 5 + (-3) = 2 19 ## 2 + (+2) = 4 20 ## 4 + (-3) = 1 21 ## 1 + (+4) = 5 22 ## 5 + (+2) = 7 23 # 24 ## Example 2 25 ## 26 ## Input: @ints = (1, 2) 27 ## Output: 1 28 # 29 ## Example 3 30 ## 31 ## Input: @ints = (1, -2, -3) 32 ## Output: 5 33 # 34 ############################################################ 35 ## 36 ## discussion 37 ## 38 ############################################################ 39 # 40 # Starting with a value of 1, we calculate the step by step 41 # sum and keep trackf of the minimum. If it is < 1, we can 42 # calculate the minimum required positive start value from 43 # that minimum step sum. Otherwise we can use 1 as the result. 44 45 use strict; 46 use warnings; 47 48 step_by_step(-3, 2, -3, 4, 2); 49 step_by_step(1, 2); 50 step_by_step(1, -2, -3); 51 52 sub step_by_step { 53 my @ints = @_; 54 print "Input: (" . join(", ", @ints) . ")\n"; 55 my $start = 1; 56 my $min = 1; 57 foreach my $elem (@ints) { 58 $start += $elem; 59 if($start < $min) { 60 $min = $start; 61 } 62 } 63 if($min < 1) { 64 my $tmp = 2 - $min; 65 print "Output: $tmp\n"; 66 } else { 67 print "Output: 1\n"; 68 } 69 }