Longest Subarray Sum = K
PHP
Hard
5 views
Problem Description
Given n integers and k, find the longest subarray with sum exactly k.
Input Format
Line1 n k. Line2 n integers.
Output Format
One integer length.
Sample Test Case
Input:
8 7
1 2 3 4 3 2 1 1
Official Solution
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$tokens=preg_split('/\\s+/', $inputText);
$i=0; $n=intval($tokens[$i++] ?? 0);
$k=intval($tokens[$i++] ?? 0);
$pos=[0=>-1];
$sum=0; $best=0;
for($idx=0;$idx<$n;$idx++){
$sum += intval($tokens[$i++] ?? 0);
$need=$sum-$k;
if(array_key_exists($need,$pos)) $best=max($best,$idx-$pos[$need]);
if(!array_key_exists($sum,$pos)) $pos[$sum]=$idx;
}
echo $best;
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!