Split into 3 Equal Sum Parts
PHP
Hard
4 views
Problem Description
Check if the array can be split into three contiguous parts with equal sum. Print YES or NO.
Input Format
First n. Next line n integers.
Official Solution
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$tokens=preg_split('/\\s+/', $inputText);
$i=0; $n=intval($tokens[$i++] ?? 0);
$a=[]; $sum=0;
for($k=0;$k<$n;$k++){ $v=intval($tokens[$i++] ?? 0); $a[]=$v; $sum+=$v; }
if($sum%3!==0){ echo 'NO'; exit; }
$target=intdiv($sum,3);
$cnt=0; $run=0;
for($k=0;$k<$n;$k++){
$run += $a[$k];
if($run===$target){
$cnt++; $run=0;
if($cnt===2 && $k<$n-1){ echo 'YES'; exit; }
}
}
echo 'NO';
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!