Exemplo n.º 1
0
/**
 * @param array $A
 * @return int
 */
function slow_solution(array $A)
{
    $profit = 0;
    $n = count($A);
    for ($i = 0; $i < $n - 1; $i++) {
        for ($k = $i + 1; $k < $n; $k++) {
            $profit = max($profit, $A[$k] - $A[$i]);
        }
    }
    return $profit;
}
/**
 * @param array $A
 * @return int
 */
function fast_solution(array $A)
{
    $max_profit = $slice_profit = 0;
    for ($i = 1, $n = count($A); $i < $n; $i++) {
        $slice_profit = max(0, $slice_profit + $A[$i] - $A[$i - 1]);
        $max_profit = max($max_profit, $slice_profit);
    }
    return $max_profit;
}
$samples = [356 => [23171, 21011, 21123, 21366, 21013, 21367], 20 => [10, 15, 14, 20, 30]];
_run_tests_($samples, 'fast_solution');
echo "Good job, Russ!";
Exemplo n.º 2
0
    $stack_pos = 0;
    foreach ($H as $cur_height) {
        while ($stack_pos > 0 && $stack[$stack_pos] > $cur_height) {
            $stack_pos--;
        }
        if ($stack_pos > 0 && $stack[$stack_pos] === $cur_height) {
            continue;
        }
        $blocks++;
        $stack[$stack_pos] = $cur_height;
        $stack_pos++;
    }
    return $blocks;
}
$samples = [7 => [8, 8, 5, 7, 9, 8, 7, 4, 8]];
_run_tests_($samples, 'solution');
/**
*
You are going to build a stone wall. The wall should be straight and N meters long, and its thickness should be constant; however, it should have different heights in different places. The height of the wall is specified by a zero-indexed array H of N positive integers. H[I] is the height of the wall from I to I+1 meters to the right of its left end. In particular, H[0] is the height of the wall's left end and H[N−1] is the height of the wall's right end.

The wall should be built of cuboid stone blocks (that is, all sides of such blocks are rectangular). Your task is to compute the minimum number of blocks needed to build the wall.

Write a function:

function solution($H);

that, given a zero-indexed array H of N positive integers specifying the height of the wall, returns the minimum number of blocks needed to build it.

For example, given array H containing N = 9 integers:

H[0] = 8    H[1] = 8    H[2] = 5