Sherlock and Array

HackerRank 問題: Sherlock and Array

Question

Watson gives Sherlock an array of integers. His challenge is to find an element of the array such that the sum of all elements to the left is equal to the sum of all elements to the right.

HackerRank 問題: Sherlock and Array

Answer

<?php

/*
 * Complete the 'balancedSums' function below.
 *
 * The function is expected to return a STRING.
 * The function accepts INTEGER_ARRAY arr as parameter.
 */

function balancedSums($number_list) {
    $sum_of_number = array_sum($number_list);

    $front_sum = 0;
    $balance_sum_status = 'NO';
    foreach ($number_list as $number_index => $number) {
        // sum number except current number
        $sum_except_current_index = $sum_of_number - $number_list[$number_index];
        if ($front_sum * 2 == $sum_except_current_index) {
            // if front sum * 2 equal sum except current number, then current number is that element
            $balance_sum_status = 'YES';
            break;
        }
        // add current number to front number
        $front_sum+=$number;
    }

    return $balance_sum_status;
}

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

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

for ($T_itr = 0; $T_itr < $T; $T_itr++) {
    $n = intval(trim(fgets(STDIN)));

    $arr_temp = rtrim(fgets(STDIN));

    $arr = array_map('intval', preg_split('/ /', $arr_temp, -1, PREG_SPLIT_NO_EMPTY));

    $result = balancedSums($arr);

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

fclose($fptr);

Reference