Task1
We find the count of maximum runs of ones:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(max);
sub consecutive_one{
max 0,map length,split /[^1]+/,join '',@{$_[0]}
}
printf "%d\n",consecutive_one([0,1,1,0,1,1,1]);
printf "%d\n",consecutive_one([0,0,0,0]);
printf "%d\n",consecutive_one([1,0,1,0,1,1]);
Task2
We subtract each price from its immediate smaller price to find the discounts:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;
sub final_price {
my ($p) = @_;
my @stack;
my @res = @$p;
foreach my $i(0..$#$p){
while(@stack && ($p->[$stack[-1]] >= $p->[$i])) {
my $j = pop @stack;
$res[$j] = $p->[$j] - $p->[$i]
}
push @stack,$i
}
@res
}
print show final_price([8,4,6,2,3]);
print show final_price([1,2,3,4,5]);
print show final_price([7,1,1,5]);
No comments:
Post a Comment