Task1
For each combination of the array of size 1 to N, we check to see if the count of zeros and ones are subset of the given x and y:
#!/usr/bin/env perl
use strict;
use warnings;
use Algorithm::Combinatorics qw(combinations);
sub ones_and_zeros{
foreach my $s(reverse 1..@{$_[0]}){
my $it = combinations($_[0],$s);
while(my $comb = $it->next){
my $joined = join '',@$comb;
my $zeroes = $joined =~ tr/0//;
my $ones = $joined =~ tr/1//;
return $s if $zeroes <= $_[1] && $ones <= $_[2]
}
}
0
}
printf "%d\n",ones_and_zeros(["10","0001","111001","1","0"],5,3);
printf "%d\n",ones_and_zeros(["10","1","0"],1,1);
Task2
We find the minimum value needed so that step-wide sum won't become less than 1:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(min max);
sub step_by_step{
my $s = 0;
my $t = $_[0]->[0];
map{$s += $_; $t = min $t,$s} @{$_[0]};
max 1,1-$t
}
printf "%d\n",step_by_step([-3,2,-3,4,2]);
printf "%d\n",step_by_step([1,2]);
printf "%d\n",step_by_step([1,-2,-3]);