Count Pairs with Sum <= X
PHP
Hard
4 views
Problem Description
Given a sorted array and X, count pairs (i
Input Format
Line1 n X. Line2 n sorted integers.
Output Format
One integer count.
Official Solution
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$tokens=preg_split('/\\s+/', $inputText);
$idx=0;
$n=intval($tokens[$idx++] ?? 0);
$x=intval($tokens[$idx++] ?? 0);
$a=[];
for($i=0;$i<$n;$i++) $a[] = intval($tokens[$idx++] ?? 0);
$l=0; $r=$n-1; $ans=0;
while($l<$r){
if($a[$l]+$a[$r] <= $x){
$ans += ($r-$l);
$l++;
}else $r--;
}
echo $ans;
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!