The Weekly Challenge 325

Longest Runs & Discounted Prices!

Original Challenge Link

Task 1: Consecutive One

"One After Another: Tracking the Longest Streak!"

Given a binary array, find the maximum number of consecutive 1s.

The Strategy: Iterate through the array while maintaining two counters: current for the length of the ongoing streak of 1s, and best for the maximum length found so far. Reset current to zero whenever a 0 is encountered. Update best whenever current exceeds it.
Perl Implementation
sub consecutive_one {
    my (@binary) = @_;
    my ($best, $current) = (0, 0);
    for my $bit (@binary) {
        if ($bit == 1) {
            $current++;
            $best = $current if $current > $best;
        } else {
            $current = 0;
        }
    }
    return $best;
}
Python Implementation
def consecutive_one(binary: list[int]) -> int:
    best = current = 0
    for bit in binary:
        if bit == 1:
            current += 1
            best = max(best, current)
        else:
            current = 0
    return best

Task 2: Final Price

"Smart Shopping: Calculating the First Available Discount!"

For each item in a list of prices, apply a discount equal to the first subsequent price that is less than or equal to the current price.

The Strategy: Use a nested loop (or a monotonic stack for better performance if the list is very large). For each price at index i, scan subsequent prices at indices j > i. The first price satisfying prices[j] <= prices[i] is our discount. Subtract it from the original price; if no such price is found, the price remains unchanged.
Perl Implementation
sub final_price {
    my (@prices) = @_;
    my @result;
    for my $i (0 .. $#prices) {
        my $price = $prices[$i];
        my $discount = 0;
        for my $j ($i + 1 .. $#prices) {
            if ($prices[$j] <= $price) {
                $discount = $prices[$j];
                last;
            }
        }
        push @result, $price - $discount;
    }
    return \@result;
}
Python Implementation
def final_price(prices: list[int]) -> list[int]:
    result = []
    n = len(prices)
    for i, price in enumerate(prices):
        discount = 0
        for j in range(i + 1, n):
            if prices[j] <= price:
                discount = prices[j]
                break
        result.append(price - discount)
    return result