Subarray Division 1

HackerRank 問題: Subarray Division 1

Question

Two children, Lily and Ron, want to share a chocolate bar. Each of the squares has an integer on it.

Lily decides to share a contiguous segment of the bar selected such that:

  • The length of the segment matches Ron’s birth month, and,
  • The sum of the integers on the squares is equal to his birth day.

Determine how many ways she can divide the chocolate.

HackerRank 問題: Subarray Division 1

Answer

<?php

/*
 * Complete the 'birthday' function below.
 *
 * The function is expected to return an INTEGER.
 * The function accepts following parameters:
 *  1. INTEGER_ARRAY s
 *  2. INTEGER d
 *  3. INTEGER m
 */

function birthday($chocolate_segment_list, $day_summing_chocolate, $month_contiguous_segment_length)
{
    $max_length_of_chocolate_segment = count($chocolate_segment_list);

    $initial_check_segment_index = 0;
    $number_way_of_divide_chocolate = 0;
    $final_check_segment_index = $initial_check_segment_index + $month_contiguous_segment_length - 1;

    while($final_check_segment_index < $max_length_of_chocolate_segment) {
        $sum_of_chocolate = 0;

        for ($check_segment_index = $initial_check_segment_index; $check_segment_index <= $final_check_segment_index; $check_segment_index++) {
            $sum_of_chocolate += $chocolate_segment_list[$check_segment_index];
            if ($sum_of_chocolate == $day_summing_chocolate && $final_check_segment_index == $check_segment_index) {
                // total chocolate equal day of summing chocolate
                // the contiguous length is equal month
                $number_way_of_divide_chocolate++;
            }

            if ($sum_of_chocolate > $day_summing_chocolate) {
                // too much chocolate
                break;
            }
        }

        // find the next chocolate segment
        $initial_check_segment_index++;
        $final_check_segment_index = $initial_check_segment_index + $month_contiguous_segment_length - 1;
    }


    return $number_way_of_divide_chocolate;
}

$fptr = fopen(getenv("OUTPUT_PATH"), "w");

$n = intval(trim(fgets(STDIN)));

$s_temp = rtrim(fgets(STDIN));

$s = array_map('intval', preg_split('/ /', $s_temp, -1, PREG_SPLIT_NO_EMPTY));

$first_multiple_input = explode(' ', rtrim(fgets(STDIN)));

$d = intval($first_multiple_input[0]);

$m = intval($first_multiple_input[1]);

$result = birthday($s, $d, $m);

fwrite($fptr, $result . "\n");

fclose($fptr);

Reference